let subject = PublishSubject<()>()
subject.subscribe {
print("Why?") // onCompleted
}
.disposed(by: disposeBag)
这是订阅的声明(来自RxSwift)
public func subscribe(onNext: ((Self.E) -> Void)? = default, onError: ((Error) -> Void)? = default, onCompleted: (() -> Void)? = default, onDisposed: (() -> Void)? = default) -> Disposable
因此,Self.E
也是Void
类型。为什么调用onCompleted
而不是onNext
?它们的语义类似(Void) -> Void
我知道,我不应该编写这样的代码(例如,我只是对这种行为感兴趣)
答案 0 :(得分:0)
在Swift中,仅当最后一个参数是闭包时,才可以省略它,并用尾随的闭包代替。您认为onCompleted
实际上是onDisposed
。您可以在以下代码中看到这一点:
var disposeBag = DisposeBag()
let subject = Observable<Void>.create { observer -> Disposable in
observer.onCompleted()
return Disposables.create()
}
subject.subscribe(onNext: { _ in
print("onNext")
}, onError: { (_) in
print("onError")
}, onCompleted: {
print("onCompleted")
}, onDisposed: {
print("onDisposed")
})
.disposed(by: disposeBag)
您将获得输出:
onCompleted
onDisposed