As someone who is relatively new to RxJs, I am looking to understand the most effective way to utilize Rx in conjunction with Promises.
I aim to create a service in Angular that functions similarly to an event dispatcher pattern, emitting an event once a promise is fulfilled. What I specifically need is for the observable to only be called if there are active subscribers to the event. Furthermore, I want subsequent subscribers to receive the same result without triggering additional requests to the server. I have successfully implemented my own solution as shown below:
// ... CountryService code
var COUNTRIES_LOADED = Rx.Observable
.create(function (observer) {
$http
.get('/countries')
.then(function (res) {
observer.onNext(res);
}, function (err) {
observer.onError(err);
})
.finally(function () {
observer.onCompleted();
});
})
.shareReplay();
When a new "listener" subscribes to the subject, the observable will fetch the data. Subsequent subscribers will receive the cached value without contacting the server again.
In my "consumer" (Angular Directive), I envision doing something like this:
// ... countryInput directive code:
COUNTRIES_LOADED.subscribe(function (response) {
// Populate countries into scope or ctrl
scope.countries = response.countries;
});
Any future subscribers to the COUNTRIES_LOADED observer must not trigger an additional $http request. Similarly, if the directive is missing from the page, $http should not be contacted at all.
While the above solution works, I am unsure of any potential drawbacks and memory implications this approach may have. Is this a valid method? Is there a better or more appropriate way to achieve this using RxJs?
Thank you very much!