简体   繁体   中英

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

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

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.

Since I stumbled upon this question trying understand the difference between those two I would like to add that for bind :

In case error occurs in debug mode, fatalError will be raised.
In case error occurs in release mode, error will be logged.

The approach is different for subscribe(onNext: which allows to explicitly handle onError: with custom handling (same for onCompleted onDisposed ).

As @chriswillow already answered both bind and subscribe(onNext: do subscribe to an observable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM