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

bufferoverflow76 picture bufferoverflow76 · Jan 28, 2018 · Viewed 9.5k times · Source

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

Answer

chriswillow picture chriswillow · Jan 28, 2018

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.