MemLeak
MemLeak

Reputation: 4640

How to build a stream in RxJs which receives data from multiple sources?

I'm trying to build a app with multiple components that consume events from the server. The app is built in Angular and is using rxjs-ng.

I have found no examples matching my use case.

For example, take a currency update where you have multiple subscribers in the UI layer and multiple providers for data-access and business logic (all on the client side).

I have implemented a client-side service which gets a currency and returns an observable:

update: function (from, to) {
    var urlForCurrencies = createConverterUrl(from, to);
    var observable = Rx.Observable.fromPromise(
        $http({method: 'JSONP', url: urlForCurrencies})
    );

    return observable;
}

and in the UI component:

var that = this;
DataService.update(currencyFrom,currencyTo).subscribe(
    function (data) {
        that.currency = data.data.CHF_EUR.val;
    },
    function (err) {
        that.error = err.message;
    }    
);

This should only work once when requested from the UI layer.

How can I send another update of the currency data or trigger an update from a different view and still use the same stream/observable?

Upvotes: 0

Views: 1447

Answers (1)

fratim
fratim

Reputation: 96

Take a look at the documentation about using subjects.

The Subject class inherits both Observable and Observer , in the sense that it is both an observer and an observable. You can use a subject to subscribe all the observers, and then subscribe the subject to a backend data source.

You could share a subject with an angular service. This way it is possible that other components can react to events using subject.subscribe(onNext, onError, onCompleted). Updates can be send via the subject using subject.onNext(...).

// Creating a subject
var subject = new Rx.Subject(); 

...

// Handing updates over to the subject
getCurrencyUpdate().then(function(data) {
  subject.onNext(data);
});

...

// Subscribe to the subject to react on updates
subscription = subject.subscribe(
  function (x) { console.log('onNext: ' + x); },
  function (e) { console.log('onError: ' + e.message); },
  function () { console.log('onCompleted'); });
)

This way you can use the subject to broadcast data to your subscribers.

Upvotes: 1

Related Questions