RxJS pushes current value towards late subscribers

Below is a snippet of HTML that I am using as an example:

<html>
<head>
    <script src="rx.all.js"></script>
</head>
<body>
    <script>
        var source = new Rx.BehaviorSubject(function() {return 2;});

        var stuff = source.scan([], function(val, operation) {
            return operation(val);
        });

        stuff.subscribe(function(v) {
            console.log("first subscriber");
            console.log(v);
        });

        source.onNext(function(val) {
            return val * 2;
        });

        stuff.subscribe(function(v) {
            console.log("second subscriber");
            console.log(v);
        });
    </script>
</body>

      

Output in JS console:

first subscriber
2
first subscriber
4
second subscriber
0 

      

Now the "stuff" does some processing (mostly by applying a function to the current value), an idea I took from the TodoMVC example for ReactJs + RxJS ( https://github.com/fdecampredon/react-rxjs-todomvc ).

The result I am trying to achieve is that the second subscriber also sees "4" when they subscribe. I am using RxJS in conjunction with ReactJS so the components are unsubscribed when they are unmounted (due to a route change) and subscribed again when they are re-mounted.

+3


source to share


1 answer


Use replay(1)

to change stuff

to a hot observable that will remember the last value and serve it to later languages:



var stuff = ...;
stuff = stuff.replay(1);

// go ahead and start it listening
// you could use .refCount() here also
var subscription = stuff.connect();

// now subscribe your observers
stuff.subscribe(...);

// send some results
source.onNext(...);
source.onNext(...);

// subscribe another observer
// will see the lastest value
// as well as any new values
stuff.subscribe(...);

source.onNext(...);
// ...

      

+5


source







All Articles