我在玩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'))


如何使可观察的对象(在函数changeStateLazy中)变得懒惰,即仅在将侦听器附加到some logic...主题(在我的情况下为state)中运行stateListener并更改状态?

最佳答案

这是我可以解决的方法。

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'))


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

10-06 06:11