2017年3月11日 星期六

[RxJS] share

 rxjs    share  


Introduction


RxJS operator : Share

Returns an observable sequence that shares a single subscription to the underlying sequence.



Sample


In this sample, I will use a scenario of searching product with RxJS and Angular to explain how rxjs:Share works.





In the above demo, we created an Observable for bringing products information from backend thru Http and created 2 Observers to show 2 messages after we click [Search] button.


let products$: Observable<Product[]>;

this.products$ = this.prodSvc.search(keyword);

var msgObserver1$ = (discount) => (data) => {
    this.toastr.info('Discount '+ discount + '% today!''Buy it now');
};

var msgObserver2$ = (keyword) => (data) => {
    this.toastr.success('See more products about ' + keyword , 'Buy it now');
};

let subscription1$ = this.products$.subscribe(msgObserver1$(10));
let subscription2$ = this.products$.subscribe(msgObserver2$(keyword));



The two subscriptions will both MAKE an EXTRA Http Request, that is not efficient. We want to share the Observable for each Observer.

PS. The first request is created by Angular
async pipe for rendering data.





Use Share() on Observable

Let’s modify the Observable with Share() and see what will happen.

this.products$ = this.prodSvc.search(keyword).share();


Now we got only one Http request on searching.





Demo





Reference



沒有留言:

張貼留言