Search code examples
javascriptfrpbacon.js

Ignore past values from FRP event stream


I am using BaconJS to create two event streams likes this:

# Wait for start of the module
sStart = Bacon.fromCallback module.onStart.bind(module)
# Watch game ticks
sTick = Bacon.fromEventTarget emitter, 'tick'
# Combine it to do something
Bacon.onValues sStart, sTick, ->
    # Do something on each tick, but only when module has been started

I want to use it for synchronization. Once the module is started, it should start listening for ticks, not sooner. It almost works, but the callback is invoked for all past ticks that has been emitted before module start instead of just recent one. Than I want to that callback being invoked for each following tick.

I am pretty much starting with FRP, there is probably some elegant way how to deal with it, but I just don't see it for now. Any ideas ?


Solution

  • Looks like you're abusing Bacon.onValues, whose purpose is to create a new stream.

    If you want to wait for the start of the module, just register the listener only when it has started:

    sTick = Bacon.fromEventTarget emitter, 'tick'
    
    module.onStart ->
      # when module has been started
      sTick.onValue ->
        # Do something on each tick
    

    For a completely FRP-style, you would use flatMap:

    sStart = Bacon.fromCallback module.onStart.bind(module)
    # Watch game ticks
    sTick = Bacon.fromEventTarget emitter, 'tick'
    # Combine it to a new stream that is made from sTicks by each sStart event
    sTicksAfterStart = sStart.flatMap -> sTick
    sTickeafterStart.onValue ->
      # Do something on each tick