flash42
flash42

Reputation: 71

How to implement polling of a REST api in Bacon.js?

I've implemented a polling logic checking the status of a RESTful service returning the status of a backend job. I've run into the problem of shutting down the polling and solved it with an "unsubBus". I'm wondering if this could be solved in a better way.

var unsubBus = new Bacon.Bus();
// Poll job status code until it's successful
var succStream = Bacon.interval(pollInterval)
    .takeUntil(unsubBus)
    .flatMapLatest(function (v) { return this.checkStatus(jobId); })
    .filter(function(v) { return v === true; });

// Unsubscribe and do something
succStream.onValue(function (_) { unsubBus.push(true); });
succStream.onValue(function (_) { DO-SOMETHING; });

Upvotes: 2

Views: 219

Answers (1)

OlliM
OlliM

Reputation: 7113

You could add .take(1) to the succStream to only take 1 value. The polling stops, as the stream has no more subscribers. Check out this jsfiddle.

// Poll job status code until it's successful
var succStream = Bacon.interval(pollInterval)
    .flatMapLatest(function (v) { return checkStatus(); })
    .filter(function(v) { return v === true; });

succStream.take(1).onValue(function (_) { log("success") });

Upvotes: 3

Related Questions