Sorry. I am confused what is binding in Rxswift. As far as I know, observable
won't produce value unless a observer subscribed on it, e.g myObservable.subscribe(onNext: {})
.
But when I read the follow line of code:
// 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)
I am confused here why the isValid
Observable is able to be observed without calling a subscribe
method on it?
Why we can just call bind(to:) in LoginViewController.swift
without calling something like viewModel.isValid.subscribe(...)
Yea, you can think of it as subscribe is for the main effect, do is for other side effects. The do operator should be pretty uncommon in your code, while subscribe is necessary. – Daniel T.
Called by the Observable when it emits an item. Takes as a parameter the item emitted by the Observable. Calls are referred to as emissions .
RxSwift: Subscribing to Observables It is the subscription that triggers an observable to begin emitting events until . error or . completed is emitted. Observing an observable is known as subscribing. Subscribe takes an escaping closure that takes an event of the supplied typed (that doesn't return anything).
RxSwift: Just Operator just operator creates an observable sequence containing just a single element and a . completed event. Type inference means we don't need to define the type.
Look at the implementation of bind(to: )
public func bind<O: ObserverType>(to observer: O) -> Disposable where O.E == E { return self.subscribe(observer) }
Subscribe is called inside.
Regarding your statement
As far as I know, observable won't produce value unless a observer subscribed on it
This is only true for cold observables. Let me quote from 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With