加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:24:45 所属栏目:百科 来源:网络整理
导读:抱歉.我很困惑Rx swift中的绑定是什么.据我所知,除非观察者订阅了它,否则observable不会产生价值,例如myObservable.subscribe(onNext:{}). 但是,当我阅读以下代码行时: // in LoginViewModel.swiftinit() { isValid = Observable.combineLatest(username.a
抱歉.我很困惑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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读