其他分享
首页 > 其他分享> > Operation之变换操作符

Operation之变换操作符

作者:互联网

buffer

let subject = PublishSubject<String>()
subject.buffer(timeSpan: 1, count: 3, scheduler: MainScheduler.instance)
    .subscribe(onNext: {print($0)})
    .disposed(by: bag)

subject.onNext("a")
subject.onNext("b")
subject.onNext("c")

subject.onNext("1")
subject.onNext("2")
subject.onNext("3")

subject.onNext("^_^")
subject.onCompleted()

window

let subject2 = PublishSubject<String>()
subject2
    .window(timeSpan: 1, count: 3, scheduler: MainScheduler.instance)
    .subscribe(onNext:{[weak self] in
        print($0)
        $0.subscribe(onNext: {print($0)}).disposed(by: self!.bag)
    })
    .disposed(by: bag)
    subject2.onNext("a")
    subject2.onNext("b")
    subject2.onNext("c")

    subject2.onNext("1")
    subject2.onNext("2")
    subject2.onNext("3")

    subject2.onNext("^_^")
    subject2.onCompleted()

map

Observable.of(1, 2, 3)
    .map{$0 * 10}
    .subscribe(onNext: { print($0) })
    .disposed(by: bag)

flatMap

let subject41 = BehaviorSubject(value: "A")
let subject42 = BehaviorSubject(value: "1")

let variable4 = Variable(subject41)

variable4.asObservable().flatMap { $0 }.subscribe(onNext: { print($0) }).disposed(by: bag)
subject41.onNext("B")
variable4.value = subject42
subject42.onNext("2")
subject41.onNext("C")

flatMapLatest

let subject51 = BehaviorSubject(value: "A")
let subject52 = BehaviorSubject(value: "1")

let variable5 = Variable(subject51)

variable5.asObservable().flatMapLatest{ $0 }.subscribe(onNext: { print($0) }).disposed(by: bag)

subject51.onNext("B")
variable5.value = subject52
subject52.onNext("2")
subject51.onNext("C")

concatMap

let subject61 = BehaviorSubject(value: "A")
let subject62 = BehaviorSubject(value: "1")

let variable6 = Variable(subject61)

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

subject61.onNext("B")
variable6.value = subject62
subject62.onNext("2") // 因为subject61还没有结束, 所以不会打印
subject61.onNext("C")
subject61.onCompleted() // 让subject61完成或者error, 上面的subject62发出的事件才会被监听到

scan

Observable.of(1,2,3,4,5)
    .scan(0) { (acum, item) -> Int in
        acum + item
}
.subscribe(onNext: { print($0) })
.disposed(by: bag)

groupBy

Observable.of(1,2,3,4,5,7,8,13)
    .groupBy { (item) -> String in
        item % 2 == 0 ? "偶数" : "奇数"
}.subscribe(onNext: { [weak self] group in
    group.asObservable().subscribe(onNext: {event in
        print("group: \(group)")
        print("key: \(group.key)")
        print("event: \(event)")
    }).disposed(by: self!.bag)
}).disposed(by: bag)

标签:Observable,变换,onNext,bag,操作符,print,let,Operation,subject
来源: https://www.cnblogs.com/gchlcc/p/11820802.html