RxSwift 操作符 (do)

do

ReactiveX:
You can register callbacks that ReactiveX will call when certain events take place on an Observable, where those callbacks will be called independently from the normal set of notifications associated with an Observable cascade. There are a variety of operators that various ReactiveX implementations have designed to allow for this.

注册一个操作符来执行可观察者的生命周期事件,它与subscribe是无关的,调用它并不影响susbscribe。

Observable<[Int]>.of([1, 2, 3])
    .do(onNext: { element in
        print("do element:" ,element)
    }, onError: { error in
        print("do error:", error)
    }, onCompleted: {
        print("do completed")
    }, onSubscribe: {
        print("do subscribe")
    }, onSubscribed: {
        print("do subscribed")
    }, onDispose: {
        print("do dispose")
    })
    .subscribe { event in
        switch event {
        case .next(let element):
            print("element:", element)
        case .error(let error):
            print("error:", error)
        case .completed:
            print("completed")
        }}
    .disposed(by: bag)

输出:
do subscribe
do subscribed
do element: [1, 2, 3]
element: [1, 2, 3]
do completed
completed
do dispose

do优先于subscribe打印。

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页