Search code examples
bacon.js

How to subscribe and unsubscribe from EventStream on the first event received?


I am trying to figure it out if there is a function in the Bacon.js API that allows to subscribe to an EventStream and when the first event fires up, the handle is unsubscribed. The way to do it that I know is the following:

let stream = new Bacon.Bus();

stream.onValue(val => {
    doSomething(val);
    return Bacon.noMore;
});

But is there something like stream.onValueOnce that automatically unsubscribe the handler after it is executed?

I also know that there is the Bacon.once that creates a EventStream that returns a single value and then ends the stream but this is not what I am looking for.

Update

As Bless Yahu sais, take or first methods can be used. To be more specific, you have to call it from the created eventStream like that:

let stream = new Bacon.Bus();

stream.first().onValue(val => {
    doSomething(val);
});

Here is a fiddle that shows it:

https://fiddle.jshell.net/3kjtwcwy/


Solution

  • How about stream.take(1)? https://baconjs.github.io/api.html#observable-take

    Or stream.first()? https://baconjs.github.io/api.html#observable-first