quinn45
quinn45

Reputation: 13

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

In RxSwift, how can I observe a BehaviorRelay just before a change happens?

I tried:

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

with which I get a notification only after the new value has been set.

Upvotes: 1

Views: 959

Answers (1)

Daniel T.
Daniel T.

Reputation: 33967

The short answer is, you can't. The work around depends on why you want the previous value. If, for example, you want to compare the previous value to the new value, you can do that with .scan. An operator like this would do it:

extension ObservableType {
    func withPrevious() -> Observable<(Element?, Element)> {
        scan((Element?.none, Element?.none)) { ($0.1, $1) }
        .map { ($0.0, $0.1!) }
    }
}

And the standard disclaimer:

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

Upvotes: 1

Related Questions