fonsp / Pluto.jl

🎈 Simple reactive notebooks for Julia
https://plutojl.org/
MIT License
4.91k stars 284 forks source link

can we get the slider value asynchronously ? #2845

Closed sonosole closed 3 months ago

sonosole commented 3 months ago

Every time I drag the slider S, the slider triggers another code C which needs the slider-value, what if i want to run S and C asynchronously, so C would not be triggered over and over again. This need could happen when i play a song, the song's volume is controlled by the slider-value. like

# S
@bind vol Slider(0:0.5:4, default=1.0)
# C
begin
    @async for chunk in wavdatas
          write(spk, chunk .* vol)
    end
end

is it possible in Pluto? I'm not using it much. Thanks !

fonsp commented 3 months ago

Hey! You could use a Ref, like so:

# S
@bind vol Slider(0:0.5:4, default=1.0)
# a Ref is like a vector with just one element
vol_ref = Ref(1.0)
vol_ref[] = vol
@bind play_song CounterButton()
# C
begin
    # use this variable here to make the button trigger this cell
    play_song

    @async let
        # by referencing vol_ref instead of vol, the slider does not trigger this cell
        vol_current = vol_ref[]
        for chunk in wavdatas
            write(spk, chunk .* vol_current)
        end
    end
end
fonsp commented 3 months ago

Hope this helps, let me know otherwise! It sounds like you're writing a fun notebook with music :)