我是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
任何人都可以帮助解释asObserver
中asObservable
,observable
或正常Subject
对象之间的区别吗?
答案 0 :(得分:1)
这是因为Subject
既是ObserverType
又是Observable
。当您致电PublishSubject
时,PublishSubject
无法从AnyObserver
键入asObserver
,因此您仍有PublishSubject
,因为它{&#39}是Observable
,仍然可以使用subscribe
等来调用