Operation之结合操作符

startWith

  • 该方法会在Observable序列开始之前插入一些事件元素. 即发生事件消息之前, 会发出这些预先插入的事件消息
Observable.of("2", "3")
    .startWith("1")
    .startWith("a")
    .startWith("b")
    .subscribe(onNext: { print($0) })
    .disposed(by: bag)

merge

  • 该方法可以将多个(两个或者两个以上的)Observable序列合并生成一个Observable序列
let subject21 = PublishSubject<Int>()
let subject22 = PublishSubject<Int>()
Observable.of(subject21, subject22)
    .merge()
    .subscribe(onNext: { print($0) })
    .disposed(by: bag)

subject21.onNext(1)
subject22.onNext(100)
subject22.onNext(110)
subject22.onNext(120)
subject21.onNext(2)

zip

  • 该方法可以将多个(两个或者两个以上的)Observable序列压缩成一个Observable序列
  • 而且他会等到每个Observable事件一一对应的凑齐之后再合并
let subject31 = PublishSubject<Int>()
let subject32 = PublishSubject<String>()
Observable.zip(subject31, subject32) {
    "\($0)\($1)"
}
.subscribe(onNext: { print($0) })
.disposed(by: bag)

subject31.onNext(1)
subject32.onNext("a")
subject31.onNext(2)
subject32.onNext("b")
subject31.onNext(3)
subject31.onNext(4)
subject31.onNext(5)

subject32.onNext("c")
subject32.onNext("d")
subject32.onNext("e")

subject32.onNext("f")
subject31.onNext(6)

subject31.onNext(7)
subject31.onNext(8)

combineLatest

  • 该方法同样是将多个(两个或者两个以上)Observable序列元素进行合并
  • 但与zip不同的是, 每当任意一个Observable有新的事件发出时, 他会将每个Observable序列的最新的一个事件元素进行合并
let subject41 = PublishSubject<Int>()
let subject42 = PublishSubject<String>()
Observable.combineLatest(subject41, subject42) {
    "\($0)\($1)"
}
.subscribe(onNext: { print($0) })
.disposed(by: bag)

subject41.onNext(1)
subject42.onNext("A")
subject41.onNext(2)
subject42.onNext("B")
subject42.onNext("C")
subject42.onNext("D")
subject41.onNext(3)
subject41.onNext(4)
subject41.onNext(5)

withLatestFrom

  • 该方法将两个Observable序列合并为一个. 每当self队列发射一个元素时, 便从第二个序列中取出最新的一个值
let subject51 = PublishSubject<String>()
let subject52 = PublishSubject<String>()

subject51.withLatestFrom(subject52)
    .subscribe(onNext: { print($0) })
    .disposed(by: bag)

subject51.onNext("A")
subject52.onNext("1")
subject51.onNext("B")
subject51.onNext("C")
subject52.onNext("2")
subject51.onNext("D")

switchLatest

  • switchLatest有点像其他语言的switch方法, 可以对事件流进行转换
  • 比如本来监听的subject1, 我可以通过更改Variable里面的value更换事件源. 变成监听subject2
let subject61 = BehaviorSubject(value: "A")
let subject62 = BehaviorSubject(value: "1")

let variable6 = Variable(subject61)

variable6.asObservable()
    .switchLatest()
    .subscribe(onNext: { print($0) })
    .disposed(by: bag)

subject61.onNext("B")
subject61.onNext("C")

// 改变事件源
variable6.value = subject62
subject61.onNext("D")
subject62.onNext("2")

// 改变事件源
variable6.value = subject61
subject62.onNext("3")
subject61.onNext("E")

posted @ 2019-11-13 14:17  Chaos_G  阅读(192)  评论(0编辑  收藏  举报