What's the difference between onValue and doAction in BaconJS?

onValue

"subscribes to a specific event handler function. The function will be called for every new value in the stream. [This is] the easiest way to assign a side effect to a thread."

On the other hand, doAction

"returns a stream / property where f is executed for each value, before being sent to subscribers."

It looks like both are just doing the function for each value in the stream. What is different between them?

+3


source to share


2 answers


The difference is that it doAction

returns the same stream, allowing side effects to be chained, and a onValue

subscribe-like function (and thus returns an unsubscribe function).



[I set out to ask this question for real, and then realized the answer when I started writing it. If someone else finds themselves in a similar situation, it might save them a few minutes.]

+5


source


The big difference is what onValue

subscribes to the stream doAction

- no. If there are no subscribers, the function inside doAction

will never be called.

var numbers1 = Bacon.fromArray([1,2,3])
numbers1.doAction(function(number) {
    alert("doAction Number " + number) // This never gets called
})


var numbers2 = Bacon.fromArray([1,2,3])
numbers2.onValue(function(number) {
    alert("onValue Number " + number) // This gets called
})

var numbersBoth = Bacon.fromArray([1,2,3])
numbersBoth
  .doAction(function(number) { console.log(number) }) // gets called
  .onValue(function(number) {
    // Do something with number
  })

      



In practice, I use it doAction

for debugging. If you want to split your side effects into separate functions, you can add multiple handlers onValue

(other than synchronous threads, but they can be made async with a simple one .delay(0)

)

+4


source







All Articles