在对一组冷的 observables 使用 combineLatest 时,我看到了一些意想不到的结果。它从除最后一个 Observable 之外的所有 Observable 中发出最新的,而是将第一个 (n-1) 个 Observable 中的最新与来自第 n 个 Observable 的每个元素相结合。
let observable = ReplaySubject<Int>.createUnbounded()
let observable2 = ReplaySubject<String>.createUnbounded()
observable.onNext(1)
observable.onNext(2)
observable.onNext(3)
observable.onNext(4)
observable2.onNext("bed")
observable2.onNext("book")
observable2.onNext("table")
let latestObserver = Observable.combineLatest(observable, observable2)
_ = latestObserver
.subscribe(onNext: {
print($0)
})
.disposed(by: disposeBag)
产生输出: (4, "bed") (4, "book") (4, "table")
我原本预计会看到(4,“table”)的输出。
如果我像这样更改可观察对象的顺序:
let latestObserver = Observable.combineLatest(observable2, observable)
我得到输出: ("table", 1) ("table", 2) ("table", 3) ("table", 4)
如果我添加一个最终的任意 Observable,那么我只会看到每个第一个的最新的:
let observable = ReplaySubject<Int>.createUnbounded()
let observable2 = ReplaySubject<String>.createUnbounded()
let observable3 = Observable<Int>.just(42)
observable.onNext(1)
observable.onNext(2)
observable.onNext(3)
observable.onNext(4)
observable2.onNext("bed")
observable2.onNext("book")
observable2.onNext("table")
let latestObserver = Observable.combineLatest(observable, observable2, observable3)
_ = latestObserver
.subscribe(onNext: {
print($0)
})
.disposed(by: disposeBag)
产生输出: (4, "table", 42)
这真的是预期的行为吗?