【问题标题】:Replay Subject from Observable (emit all previous events)从 Observable 重放主题(发出所有以前的事件)
【发布时间】:2019-05-27 10:29:38
【问题描述】:

我有一个 observable,我正在尝试从中创建一个重播主题。它应该发出 observable 发出的当前和所有以前的事件。

根据answer,这是我认为可行的方法:

// create an observable from dummy array and a blank replay subject
const observable$ = from([1, 2, 3])
const replay$ = new ReplaySubject()

// create a replay subject from the observable (not working as expected)
observable$.subscribe(replay$)

// log out the events
observable$.subscribe(e => console.log('observable', e) )
replay$.subscribe(e => console.log('replay', e))

日志

observable 1
observable 2
observable 3
replay 1
replay 2
replay 3

我正在寻找的行为是重播主题也会发出以前的事件,如下所示:

replay [1]
replay [1, 2]
replay [1, 2, 3]

我怎样才能归档这个?

【问题讨论】:

    标签: rxjs observable


    【解决方案1】:

    ReplaySubject 仅在订阅时重播整个序列。这意味着仅当您致电replay$.subscribe() 时。之后它只通过所有排放。

    从您想要获得的输出来看,您似乎想要将其与scan() 链接起来,因为ReplaySubject 会逐一发出项目,而不是像您期望的那样累积数组。

    observable$.pipe(
      scan((acc, val) => [...acc, val], []),
    ).subscribe(replay$);
    

    现场演示:https://stackblitz.com/edit/rxjs-yfgkvf?file=index.ts

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      相关资源
      最近更新 更多