Delayed subscription to flatMap doesn't works as expected

16 views
Skip to first unread message

Dmitry Kourmyshov

unread,
Apr 4, 2016, 8:28:45 PM4/4/16
to Bacon.js
Consider a short snippet:

var init = Bacon.later(100, {init: true});

var prop = Bacon.when([init], function () {
 
return {field: Bacon.repeatedly(1000, [1, 2, 3])};
}).flatMap('.field'); //.toProperty(0);

//prop.onValue(function() {});

init
.onValue(function () {
  prop
.onValue(function (value) {console.log(value);});
});

No values from flatMap would be printed to console by handler. If dummy subscriber immediately after flatMap will be uncommented, the delayed subscriber also will get values. If flatMap output will be converted to Property, without the dummy sink the delayed sink will get only initial value.

It seems to be the case when the flatMap and its delayed subscription depend on the same stream; following code will print out values, even though the delays are equal (and will continue to work if init1 will be made before or after init2):

var init1 = Bacon.later(100, {init: true});
var init2 = Bacon.later(100, {init: true});

var prop = Bacon.when([init1], function () {
 
return {field: Bacon.repeatedly(1000, [1, 2, 3])};
}).flatMap('.field'); //.toProperty(0);

//prop.onValue(function() {});

init2
.onValue(function () {
  prop
.onValue(function (value) {console.log(value);});
});


Is this a bug or some normal behavour of flatMap I am not yet understand?

Sincerely,
Dmitry

Juha Paananen

unread,
Apr 5, 2016, 2:52:28 AM4/5/16
to Dmitry Kourmyshov, Bacon.js
Dmitry,

This might not seem intuitive but it is “just how it works”. In the first case, the init stream has already produced its first and only value when you subscribe to prop

The uncommenting affects the situation because it causes prop to subscribe to its sources (i.e. init) so that it won’t miss the event from init.

All observables subscribe to their underlying sources “lazily”, i.e. when they have a reason to. This is a desirable thing, as it, in most cases, takes care of resource management automatically, so you don’t have to remember to unsubcribe from underlying data sources yourself.

Cheers,
Juha

--
You received this message because you are subscribed to the Google Groups "Bacon.js" group.
To post to this group, send email to bac...@googlegroups.com.
Visit this group at https://groups.google.com/group/baconjs.

Reply all
Reply to author
Forward
0 new messages