0

I have a stream which produces many events. I only want to take the first event to activate certain stuff when that happens.

My first thought was to use stream.first().subscribe(activateStuff) to achieve that. The problem is that the activateStuff handler is getting called twice. But if I use onValue instead of subscribe, it will get called just once (as expected).

Interestingly, if I remove the first() part and I use subscribe with just one event being fired, it will behave like onValue (both of them calling activateStuff just once).

let stream1 = new Bacon.Bus();
stream1.first().onValue(() => console.log("from stream1"));
stream1.push({});
// it will print from stream1 once

let stream2 = new Bacon.Bus();
stream2.first().subscribe(() => console.log("from stream2"));
stream2.push({});
// it will print from stream2 twice. Why !?

let stream3 = new Bacon.Bus();
stream3.onValue(() => console.log("from stream3"));
stream3.push({});
// it will print from stream3 once

let stream4 = new Bacon.Bus();
stream4.subscribe(() => console.log("from stream4"));
stream4.push({});
// it will print from stream4 once

What is wrong here using first() and then subscribe() with the same event stream?

You can play with the code here: https://fiddle.jshell.net/np0r80fn/

Daniel San
  • 1,937
  • 3
  • 19
  • 36

1 Answers1

0

The subscribe method will call your method with Event (https://github.com/baconjs/bacon.js/#event) objects instead of just new values. You get 2 callbacks: one for the actual value wrapped in a Next event and another for the End event. If you remove the .first() part, the resulting stream will not end; that's why you get just one callback in that case.

raimohanska
  • 3,265
  • 17
  • 28