在RxSwift中asObserver,asObservable和none之间的区别是什么

时间:2016-09-03 09:52:30

标签: swift reactive-programming rx-swift

我是RxSwift和Reactive编程的新手。这是我的代码:

let disposeBag = DisposeBag()
  let dartScore = PublishSubject<Int>()
  dartScore.asObserver()
    .scan(501, accumulator: {
      intermediate, newValue in
      var result = intermediate - newValue
      return result >= 0 ? result : intermediate
    })
    .do(onNext: {
      if $0 == 0 {
        dartScore.onCompleted()
      }
    })
    .subscribe(onNext:{print($0)}, onCompleted:{print("Game over")})
    .addDisposableTo(disposeBag)

  dartScore.onNext(13)
  dartScore.onNext(60)
  dartScore.onNext(50)
  dartScore.onNext(0)
  dartScore.onNext(0)
  dartScore.onNext(378)

您可能会注意到dartScore.asObserver()。如果我删除.asObserver()或将其替换为.asObservable(),则最终结果相同:

488
428
378
378
378
Game over

任何人都可以帮助解释asObserverasObservableobservable或正常Subject对象之间的区别吗?

1 个答案:

答案 0 :(得分:1)

这是因为Subject既是ObserverType又是Observable。当您致电PublishSubject时,PublishSubject无法从AnyObserver键入asObserver,因此您仍有PublishSubject,因为它{&#39}是Observable,仍然可以使用subscribe等来调用