【发布时间】:2021-03-01 19:14:48
【问题描述】:
我知道使用 Rx 的 flatmap 或 flatmapLatest 比嵌套订阅更可取。但是,我找不到令人信服的理由说明嵌套订阅调用“应该不惜一切代价避免”(RxSwift Github Tips),并且想了解原因。
除了“不良代码气味”之外,对具体问题有任何见解吗?
示例 (source):
使用嵌套订阅(错误)
textField.rx.text.subscribe(onNext: { text in
performURLRequest(text).subscribe(onNext: { result in
...
})
.disposed(by: disposeBag)
})
.disposed(by: disposeBag)
使用 flatmapLatest(好)
textField.rx.text
.flatMapLatest { text in
// Assuming this doesn't fail and returns result on main scheduler,
// otherwise `catchError` and `observeOn(MainScheduler.instance)` can be used to
// correct this.
return performURLRequest(text)
}
...
.disposed(by: disposeBag) // only one top most disposable
【问题讨论】:
标签: ios swift system.reactive rx-swift