• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

[RxJS] Share vs ShareReply

开发技术 开发技术 8小时前 2次浏览

https://www.learnrxjs.io/learn-rxjs/operators/multicasting/sharereplay

https://www.learnrxjs.io/learn-rxjs/operators/multicasting/share

 

Share and ShareReplay, they are mainly the same. Just for ShareReplay, the subscriber subscribe after event emitted can also get value, similar to ReplaySubject.

 

// simulate url change with subject
const routeEnd = new Subject();

// grab url and share with subscribers
const lastUrl = routeEnd.pipe(
  pluck('url'),
  share()
);

// initial subscriber required
const initialSubscriber = lastUrl.subscribe(console.log); // nothing

// simulate route change
routeEnd.next({data: {}, url: 'my-path'});

// nothing logged
const lateSubscriber = lastUrl.subscribe(console.log); // my-path

In the code, only lateSubscribe got the value. initialSubscribe didn’t get the value.

 

import { Subject } from 'rxjs/Subject';
import { ReplaySubject } from 'rxjs/ReplaySubject';
import { pluck, share, shareReplay, tap } from 'rxjs/operators';

// simulate url change with subject
const routeEnd = new Subject<>();

// grab url and share with subscribers
const lastUrl = routeEnd.pipe(
  tap(_ => console.log('executed')),
  pluck('url'),
  // defaults to all values so we set it to just keep and replay last one
  shareReplay(1)
);

// requires initial subscription
const initialSubscriber = lastUrl.subscribe(console.log);

// simulate route change
// logged: 'executed', 'my-path'
routeEnd.next({data: {}, url: 'my-path'});

// logged: 'my-path'
const lateSubscriber = lastUrl.subscribe(console.log);

Both got the value.


程序员灯塔
转载请注明原文链接:[RxJS] Share vs ShareReply
喜欢 (0)