是否有可能让`ReplaySubject`在订阅时运行闭包?

时间:2016-09-08 07:27:53

标签: swift rx-swift reactivex

我想创建一个cold observable,如果有实际的订阅,它只会开始执行昂贵的操作。 ReplaySubject很适合除了我需要能够在进行实际订阅时启动昂贵的后台操作而不是创建可观察对象的部分。有办法吗?某种onSubscribed { ... }方法。

1 个答案:

答案 0 :(得分:1)

以下是几个选项:

将昂贵的操作添加到doOn(onSubscribe:)和订阅之间的Observable

let observable = Observable.of(1, 2)
    .doOn(onSubscribe: { _ in
        expensiveOperation()
    })

observable
    .subscribeNext { e in
        print(e)
    }

使Observable可连接并分隔doOn(onSubscribe:)

let observable = Observable.of(1, 2)
    .publish()

observable
    .doOn(onSubscribe: { _ in
        expensiveOperation()
    })
    .subscribe()

observable
    .subscribeNext { e in
        print(e)
    }

observable.connect()