抱歉.我很困惑Rx
swift中的绑定是什么.据我所知,除非观察者订阅了它,否则observable不会产生价值,例如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?为什么我们可以在LoginViewController.swift中调用bind(to :)而不调用viewmodel.isValid.subscribe(…)之类的东西
看看bind(to :)的实现
原文链接:https://www.f2er.com/swift/319101.htmlpublic 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
这只适用于寒冷的观察者.让我引用这个site
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.