Search code examples
javascriptrxjsfrpbacon.js

What is lazy evaluation in Bacon.js?


I am not able to understand what is lazy evaluation in Bacon.js.

I wrote the example provided by Bacon using map and flatMap and I get the same result.

Here is the HTML

<input id="itemname" type="text" />
<input id="additem" type="button" value="Add Item" />
<input id="purchase" type="button" value="Purchase" />

Here is the JS for code using map

var items = $("#additem").asEventStream("click").map(function(e){
    console.log("Executing");
    return document.getElementById("itemname").value;
}).toProperty();

var submittedItems = items.sampledBy($("#purchase").asEventStream("click"));

Here is the JS for code using flatMap

var items = $("#additem").asEventStream("click").flatMap(function(e){
    console.log("Executing");
    return document.getElementById("itemname").value;
}).toProperty();

var submittedItems = items.sampledBy($("#purchase").asEventStream("click"));

For both the version of JS there is nothing logged even if I click the buttons. According to documentation the second one should output "Executing" message on the console.

Both the code works if I attach a subscriber using onValue.

Please help me understand what's wrong?


Solution

  • When you create a stream that is based on another stream, for example by calling stream.sampledBy(...), that does not subscribe to the original stream. Regardless of how many create-stream-from-stream functions you chain together. So $("#additem").asEventStream("click") does not cause a subscription, and neither does .map(...) or .toProperty();.

    An actual subscription is only made when calls that are specifically documented as to subscribe to the stream. They are listed under "Common methods in EventStreams and Properties" here: https://baconjs.github.io/api.html - i.e. subscribe(), onValue(), onValues(), onError() and onEnd(). If you don't care about the events you could just use submittedItems.onEnd(function(){}); which is never actually called since your streams never end.