Pergunta

I am taking small steps in FRP land with BaconJS. I have the following code:

# This will eventually get resolved with some value
dfd = Promise.defer()
promised = Bacon.fromPromise dfd.promise

# Values are occasionally being pushed in here
bus = new Bacon.Bus

# 1. attempt
bus.combine promised, (fromBus, fromPromise) ->
   # This is never invoked

# 2. attempt
Bacon.combineAsArray( bus, promised ).onValues (fromBus, fromPromise) ->
   # This is invoked only once for the latest value from the bus

# 3. attempt
promised.sampledBy(bus).onValue (fromPromise, fromBus) ->
   # No invoke here at all

# These are called asynchronously during application lifespan
bus.push obj1
dfd.resolve value
bus.push obj2
bus.push obj3

I want to update every delivered object through Bus with the value from the promise object including those, that were pushed there before promise was resolved. I could do something this:

bus.onValue (fromBus) ->
    promise.then (fromPromise) ->
        ...

Yes, that works, but I just don't like it and I want to see if FRP can solve it more elegantly. Do you have any hints how do it pure FRP way, please ?

Update

I was thinking about some other approaches. Here is some background what's going on actually...

# Simple function that creates some object instance (if it haven't been created yet ) and returns it
getObject = (name) ->
   unless obj = list[name]
     obj = new Obj()
     bus.push obj

For every object added to the cache I need to set some property to value that comes from the Promise. Basically I could do it like this:

obj = new Obj()
dfd.promise.then (resolvedValue) ->
    obj.someProperty = resolvedValue

This is perfectly viable solution without FRP, however as you may know, every .then call is forced to be asynchronous. It pays it's price with lowered performance. I would like to overcome this. If I understand it correctly, using FRP it would call .then just once and then provide static value. Question remains how to do it...

Solved

Check out fiddle. In short, it can look like this:

bus.flatMap(
    Bacon.combineAsArray.bind Bacon, promised
).onValue ([fromPromise, fromBus]) ->
    fromBus.specialProperty = fromPromise
Foi útil?

Solução

Looks like you're looking for flatMap (again):

busValuesWithPromise = bus.flatMap (busValue) ->
    Bacon.combineAsArray(promised, busValue)
busValuesWithPromise.onValues (fromPromise, fromBus) ->
    # every bus update, together with the promise value
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top