如何在rxjs上创建可重放的事件总线

时间:2018-06-07 11:09:10

标签: events rxjs

我需要创建一个包含我的应用程序的所有事件的事件流,我需要该流可以重放并且能够(如果需要)将旧事件广播到以后的初始化服务。

所以我尝试使用ReplaySubject,但后来却不知道运营商,以避免在必要时重播:

import {ReplaySubject, of} from 'rxjs'
import {combineLatest} from 'rxjs/operators'

const bus$ = new ReplaySubject
const one$ = of(1)

// later
bus$.next('foo')
bus$.next('bar')
bus$.next('baz')

// Then I want to subscribe and know about the older events also
bus$.subscribe(doSomething)

// Or I just want the latest values from the subject
bus$
  .pipe(
    combineLatest(one$), 
    // take only the real value from the bus
    map(x => x[0]),
  )
  .subscribe(doSomething)

我发现只有这种人为的解决方案...我想有一个操作员,或者我的解决方案完全错了,而且有一种完全不同的方法......

提前致谢!

更新

使用rxjs 6我已经完善了当前的解决方案:

import {ReplaySubject, EMPTY} from 'rxjs'
import {combineLatest} from 'rxjs/operators'
import {unary} from 'ramda'

const eventsBus = new ReplaySubject()

export const events$ = eventsBus
export const latestEvents$ = events$.pipe(combineLatest(EMPTY, unary))

1 个答案:

答案 0 :(得分:0)