RXJS。懒惰可观察

时间:2017-12-06 23:47:50

标签: javascript rxjs reactive-programming

我正在尝试理解一个概念rxjs:反应性编程应该是懒惰的。如果没有一个订户附加到一个可观察者,它就不应该产生价值。这是我的例子:

const Rx = require('rxjs')

const state = new Rx.Subject()

const changeStateLazy = (args) =>
    Rx.Observable.of(args)
        // some logic, e.g. REST requests
        .do(val => state.next('new state'))

changeStateLazy(42)

const stateListener = state.subscribe(
    val => console.log('state.next: ', val),
    err => console.log('state.error: ', err),
    () => console.log('state.complete'))

如何使observable(函数changeStateLazy)延迟,即运行some logic...并仅在监听器附加到state主题时改变状态(在我的情况下它&# 39; s stateListener)?

2 个答案:

答案 0 :(得分:1)

以下是我如何管理它。

const Rx = require('rxjs')

const lazyStateModifier = new Rx.ReplaySubject(1)
    .map(args => {
        console.log('>some logic. args: ', args)
        return {status: 'OK', result: 'new state'}
    })
    .map(res => res.result)

const state = new Rx.Subject().merge(lazyStateModifier)

const changeStateLazy = (args) =>
    lazyStateModifier.next(args)

console.log('>invoke changeStateLazy')
changeStateLazy(42)

console.log('>subscribe')
state.subscribe(
    val => console.log('state.next: ', val),
    err => console.log('state.error: ', err),
    () => console.log('state.complete'))

希望有一个更好的解决方案,而不是将每个懒惰的观察者合并到国家......

答案 1 :(得分:0)

不完全确定要实现的目标,但如果要在订阅观察者时输出LAST值,请尝试" AsyncSubject"。

const state = new Rx.AsyncSubject();

要使AsyncSubject起作用,它需要调用完整的方法。

const changeState = () =>
    Rx.Observable.of(1)
       .subscribe(val => {
          state.next('new state');
          state.complete();
        });

如果您希望它的行为不同,您可能需要使用" BehaviorSubject"," BehaviorSubject"等。