Search code examples
rx-swift

Get last value from Observable


How can combineLatest be used to return a BehaviorSubject? I'm trying to get the last value out of the observable.

var things: Observable<Thing>

// driven by UI
var selectedThingIndex: PublishSubject<Int>

// this is a BehaviorSubject, because I need to get the latest value outside a subscriber
var currentThing: BehaviorSubject<Thing> = BehaviorSubject.combineLatest(things, selectedThingIndex) { things, index in
    things[index]
}

// Get the last value
let thing = currentThing.value()

I can't get this to compile, because combineLatest returns an Observable, which doesn't seem to be castable to a BehaviorSubject. I tried an explicit cast, e.g. as? BehaviorSubject<Thing?> but that returns nil.


Solution

  • You will have to create the BehaviorSubject and then bind your combined observable to it:

    let currentThing = BehaviorSubject<Thing?>(value: nil)
    Observable.combineLatest(things, selectedThingIndex) { $0[$1] }
        .bind(to: currentThing)
        .disposed(by: bag)