在变化发生之前观察 RxSwift.BehaviorRelay

Observe an RxSwift.BehaviorRelay just **before** a change happens

在 RxSwift 中,我怎样才能观察到 BehaviorRelay 发生变化之前

我试过了:

object.subscribe(onNext: {...})

只有在设置新值后我才会收到通知。

简而言之,你不能。解决方法取决于您想要先前值的原因。例如,如果您想要将先前的值与新值进行比较,您可以使用 .scan 来完成。像这样的操作员会这样做:

extension ObservableType {
    func withPrevious() -> Observable<(Element?, Element)> {
        scan((Element?.none, Element?.none)) { ([=10=].1, ) }
        .map { ([=10=].0, [=10=].1!) }
    }
}

标准免责声明:

Subjects [and Relays] provide a convenient way to poke around Rx, however they are not recommended for day to day use... Instead of using subjects, favor the factory methods... -- Intro to Rx