Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rxswift observable bind(to:) vs subscribe(onNext:)

Tags:

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(...)

like image 289
bufferoverflow76 Avatar asked Jan 28 '18 09:01

bufferoverflow76


People also ask

Do vs subscribe in RxSwift?

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.

What is Onnext in RxSwift?

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 .

What is subscribe in RxSwift?

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).

What is observable just RxSwift?

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.


1 Answers

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.

like image 92
christopher.online Avatar answered Sep 17 '22 15:09

christopher.online