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

实验

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

1
2
3
4
5
6
7
let observer = Observable<Any>.create { (observer) -> Disposable in
observer.onNext("next")
observer.onError(LJError.faild)
//observer.onCompleted()
return Disposables.create()
}

转换成Driver并订阅

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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信号,查看输出

1
2
3
4
// output:
driver onNext: next
driver onCompleted
driver onDisposed

只发送 next信号

1
driver onNext: next

结论

我们可以发现:

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

所以,如果要处理错误信号,应该使用Observable。如果不产生错误信号,使用Driver