Search code examples
javascriptreactive-programmingrxjsbacon.js

What is the RxJS equivalent of Bacon.js bus?


How can I create an Observable that I can just directly push events to, like with Bacon.js's Bus?


Solution

  • The equivalent in RxJS is called Subject. It is both an Observer and an Observable. So to push events to it, you use it's Observer interface: the onNext, onError, and onCompleted methods. Then you can subscribe to it, map, zip, filter it like any Observable. Here's an example from the official docs:

    var subject = new Rx.Subject();
    
    var subscription = subject.subscribe(
        function (x) { console.log('onNext: ' + x); },
        function (e) { console.log('onError: ' + e.message); },
        function () { console.log('onCompleted'); });
    
    subject.onNext(1);
    // => onNext: 1
    
    subject.onNext(2);
    // => onNext: 2
    
    subject.onCompleted();
    // => onCompleted
    
    subscription.dispose();
    

    You can check the Subject getting started guide here, and the Subject API docs here.