RxSwift-Observable asDriver后的事件订阅关系

实验

创建一个Observable信号,发送next和error信号

let observer = Observable.create { (observer) -> Disposable in
                  observer.onNext("next")
                  observer.onError(LJError.faild)
                  //observer.onCompleted()

                  return Disposables.create()
                }

转换成Driver并订阅

observer.asDriver(onErrorJustReturn: "driver error")
            .drive(onNext: { (next) in
                print("driver onNext: \(next)")
            }, onCompleted: {
                print("driver onCompleted")
            }, onDisposed: {
                print("driver onDisposed")
            })
            .disposed(by: disposed)

// output:
driver onNext: next
driver onNext: driver error
driver onCompleted
driver onDisposed


发送next和completed信号,查看输出

// output:
driver onNext: next
driver onCompleted
driver onDisposed

只发送 next信号

driver onNext: next

结论

我们可以发现:

  1. observer.onNext() 可以触发 drive(onNext: {})
  2. observer.onError() 也可触发 drive(onNext: {}), 但是返回的不是error信息,是onErrorJustReturn的值
  3. observer.onError()observer.onCompleted() 都会触发 .drive(onCompleted:{})

你可能感兴趣的:(RxSwift-Observable asDriver后的事件订阅关系)