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

前端之家收集整理的这篇文章主要介绍了Rxswift observable bind(to :) vs subscribe(onNext :)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
抱歉.我很困惑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 :)的实现
public 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

@H_404_19@

这只适用于寒冷的观察者.让我引用这个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.

@H_404_19@
原文链接:https://www.f2er.com/swift/319101.html

猜你在找的Swift相关文章