How do reactive streams in JS work?

Viewed 641

I'm novice in reactive streams and now trying to understand them. The idea looks pretty clear and simple, but on practice I can't understand what's really going on there.

For now I'm playing with most.js, trying to implement a simple dispatcher. The scan method seems to be exactly what I need for this.

My code:

var dispatch;
// expose method for pushing events to stream:
var events = require("most").create(add => dispatch = add); 
// initialize stream, so callback in `create` above is actually called
events.drain();

events.observe(v => console.log("new event", v));

dispatch(1);

var scaner = events.scan(
  (state, patch) => {
    console.log("scaner", patch);
    // update state here
    return state;
  },
  { foo: 0 }
);

scaner.observe(v => console.log("scaner state", v));

dispatch(2);

As I understand, the first observer should be called twice (once per event), and scaner callback and second observer – once each (because they were added after triggering first event).

On practice, however, console shows this:

new event 1
new event 2
scaner state { foo: 0 }

Scaner is never called, no matter how much events I push in stream.

But if I remove first dispatch call (before creating scaner), everything works just as I expected.

Why is this? I'm reading docs, reading articles, but so far didn't found anything even similar to this problem. Where am I wrong in my suggestions?

2 Answers
Related