对不起。我对 Rxswift 中绑定(bind)的内容感到困惑。据我所知,除非观察者订阅它,否则 observable
不会产生值(value),例如 myObservable.subscribe(onNext: {})
。
但是当我阅读以下代码行时:
// in LoginViewModel.swift
init() {
isValid = Observable.combineLatest(username.asObservable(), password.asObservable()) { (username, password) in
return !username.isEmpty && !password.isEmpty
}
}
// in LoginViewController.swift
viewModel.isValid.bind(to: loginButton.rx.isEnabled).disposed(by: disposeBag)
我在这里很困惑,为什么不用调用 subscribe
方法就可以观察到 isValid
Observable?
为什么我们可以只调用 bind(to :) 在 LoginViewController.swift
中而不调用像 viewModel.isValid.subscribe(...)
最佳答案
看bind(to:)
的实现
public func bind<O: ObserverType>(to observer: O) -> Disposable where O.E == E {
return self.subscribe(observer)
}
订阅是在内部调用的。
关于你的陈述
As far as I know, observable won't produce value unless a observer subscribed on it
这仅适用于冷 observables。让我引用 RxSwift docs
When does an Observable begin emitting its sequence of items? It depends on the Observable. A “hot” Observable may begin emitting items as soon as it is created, and so any observer who later subscribes to that Observable may start observing the sequence somewhere in the middle. A “cold” Observable, on the other hand, waits until an observer subscribes to it before it begins to emit items, and so such an observer is guaranteed to see the whole sequence from the beginning.
关于swift - Rxswift 可观察绑定(bind)(到 :) vs subscribe(onNext:),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48485091/