【问题标题】:how to use multicasting obs with behavioursubject?如何将多播 obs 与行为主题一起使用?
【发布时间】:2020-05-26 21:37:10
【问题描述】:

一般来说,我们需要行为主体功能。但只有在第一次订阅时,我们才应该将订阅发送到 REST 中的服务器。并在最后一次取消订阅时发送取消订阅,并且所有订阅的后期观察者将 gwt 从第一个接收到的最新 json。我可以使用 rxjs 操作符来做到这一点吗?怎么做?还是我应该使用自定义 obserbale ?

目前的自定义代码是这样的:

public observable: Observable<TPattern> = new Observable((observer: Observer<TPattern>) => {
 this._observers.push(observer);
 if (this._observers.length === 1) {
  this._subscription = this.httpRequestStream$
    .pipe(
      map((jsonObj: any) => {
        this._pattern = jsonObj.Data;
        return this._pattern;
      })
    )
    .subscribe(
      (data) => this._observers.forEach((obs) => obs.next(data)),
      (error) => this._observers.forEach((obs) => obs.error(error)),
      () => this._observers.forEach((obs) => obs.complete())
    );
}
if (this._pattern !== null) {
  observer.next(this._pattern); // send last updated array
}
return () => {
  const index: number = this._observers.findIndex((element) => element === observer);
  this._observers.splice(index, 1);
  if (this._observers.length === 0) {
    this._subscription.unsubscribe();
    this._pattern = null; // clear pattern when unsubscribed
  }
};

});

【问题讨论】:

  • 你能举一个具体的例子来说明你在寻找什么吗?例如'给定X,我想实现Y'
  • 与标准BehaviorSubject有什么区别?您可以将其与multicast(new BehaviorSubject) 一起使用

标签: rxjs rxjs-pipeable-operators rxjs-observables


【解决方案1】:

听起来您需要shareReplay(1),它将与所有订阅者分享最新的回复。

const stream$ = httpRequestStream$.pipe(
  shareReplay(1),
),

stream$.subscribe(); // sends the request and gets its result
stream$.subscribe(); // doesn't send it but gets cached result
stream$.subscribe(); // doesn't send it but gets cached result
stream$.subscribe(); // doesn't send it but gets cached result

【讨论】:

  • 谢谢,听起来像是要走的路,但是当 httpRequestStream$ 获得新结果(从 websocket 获取)时,所有订阅者都会获得新结果吗?以及取消订阅在这个实现中是如何工作的? strem 和 httpRequestStream$ 也应该是 behaviorSubjects?
  • 如果它发出,每个人都会收到新值的通知。当每个人都取消订阅时,它会关闭订阅,如果 httpRequestStream$ 完成,那么订阅也完成。是的,它可以是 BehaviourSubject 或任何其他 Observable。
  • 啊谢谢伙计。为了安全起见,我添加了当前代码做我想要实现的目标,shareReplay 可以替换它吗?
  • 就是这样。用.pipe(shareReplay(1)) 包裹this.httpRequestStream$,你就可以开始了。
  • 包装 this.httpRequestStream$ 是什么意思?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多