swift - Rxswift 可观察绑定(bind)(到 :) vs subscribe(onNext:)

标签 swift rx-swift

对不起。我对 Rxswift 中绑定(bind)的内容感到困惑。据我所知,除非观察者订阅它,否则 observable 不会产生值(value),例如 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?
为什么我们可以只调用 bind(to :) 在 LoginViewController.swift 中而不调用像 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

这仅适用于 observables。让我引用 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.

关于swift - Rxswift 可观察绑定(bind)(到 :) vs subscribe(onNext:),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48485091/

相关文章:

忽略返回值的Swift范围?

swift - 访问由脚本 Swift 创建的根文件

swift - Firebase 身份验证电话号码

ios - RxDataSources Collection View 单元格始终使用淡入淡出来插入单元格动画,无法更改为不同的动画

swift - 用于多阶段蓝牙命令的 RxBluetoothKit 代码模式

ios - 如何在多个类上调用同一个函数?

swift - 结构是文件私有(private)的,不能从 swift 4.1 中的默认参数值引用

ios - RxSwift 可观察竞争条件

ios - 如何使用 RxSwift 将一种类型的 Observable 数组转换为不同类型的 Observable 数组

ios - RxAlamofire - 下载完成事件丢失