从Observable获取最后一个值

时间:2019-02-03 20:43:11

标签: rx-swift

如何使用combineLatest返回BehaviorSubject?我正在尝试从可观察值中获取最后一个值。

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

我无法编译它,因为combineLatest返回了Observable,它似乎无法转换为BehaviorSubject。我尝试了一个明确的演员表,例如as? BehaviorSubject<Thing?>,但返回nil。

1 个答案:

答案 0 :(得分:1)

您将必须创建BehaviorSubject,然后将组合的可观察对象绑定到该行为:

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