【发布时间】:2018-10-09 12:43:21
【问题描述】:
今天我将我的代码从 ReactiveSwift 迁移到 RxSwift 并遇到了这个奇怪的场景。
我在ViewModel 类中有一个Observable 与withLatestFrom 运算符组成,它仅在我在编写它时在ViewModel 类的初始化程序中进行的测试订阅上发出,但是不在我在ViewController 的订阅中。
来自此 Observable 的 withLatestFrom 运算符正在接受另一个 Observable,它也由 withLatestFrom 运算符作为其参数组成。
// emit phrases when viewDidLoad emits
let thePhrases = self.viewDidLoadSubject.withLatestFrom(self.configureWithPhrasesSubject)
// This is the problematic Observable
let printThePhrases = self.buttonTappedSubject.withLatestFrom(thePhrases)
这是我为展示这种奇怪行为而编写的代码,您可以在 XCode 中运行它并将调试器输出过滤器设置为 [!] 以忽略模拟器产生的垃圾输出:
import UIKit
import RxSwift
public final class RxTestViewModel {
public init() {
// emit configuredWithPhrases when viewDidLoad emits
let configPhrases = self.viewDidLoadSubject
.withLatestFrom(self.configureWithPhrasesSubject)
.filter { $0 != nil }
.map { $0! }
// Show phrases to be printed on viewDidLoad
self.toBePrinted = configPhrases.asObservable()
_ = self.toBePrinted.subscribe(onNext: {
print("[!][\(Thread.current)] -- ViewModel.toBePrinted.onNext -> \($0)")
})
// Print first phrase whenever buttonTapped() is called
self.printSomething = self.buttonTappedSubject
.withLatestFrom(self.configureWithPhrasesSubject
.filter { $0 != nil }
.map { $0! })
_ = self.printSomething.subscribe(onNext: {
print("[!][\(Thread.current)] -- ViewModel.printSomething.onNext -> \($0)")
})
}
// MARK: Inputs
private let configureWithPhrasesSubject = BehaviorSubject<[String]?>(value: nil)
public func configureWith(phrases: [String]) {
print("[!][\(Thread.current)] -- ViewModel.configureWith")
self.configureWithPhrasesSubject.on(.next(phrases))
}
private let viewDidLoadSubject = PublishSubject<Void>()
public func viewDidLoad() {
print("[!][\(Thread.current)] -- ViewModel.viewDidLoad")
self.viewDidLoadSubject.on(.next( () ))
}
private let buttonTappedSubject = PublishSubject<Void>()
public func buttonTapped() {
print("[!][\(Thread.current)] -- ViewModel.buttonTapped")
self.buttonTappedSubject.on(.next( () ))
}
// MARK: Outputs
public let printSomething: Observable<[String]>
public let toBePrinted: Observable<[String]>
}
public final class RxTestViewController: UIViewController {
private let button: UIButton = UIButton()
private let viewModel: RxTestViewModel = RxTestViewModel()
public static func instantiate() -> RxTestViewController {
let vc = RxTestViewController()
vc.viewModel.configureWith(phrases: ["First phrase", "Second phrase", "Third phrase"])
return vc
}
}
extension RxTestViewController {
public override func viewDidLoad() {
super.viewDidLoad()
self.setupButton()
self.setupViewModel()
self.viewModel.viewDidLoad()
}
}
extension RxTestViewController {
private func setupViewModel() {
_ = self.viewModel.toBePrinted
.subscribeOn(ConcurrentMainScheduler.instance)
.subscribe(onNext: {
print("[!][\(Thread.current)] -- RxTestViewController.toBePrinted.onNext -> \($0)")
self.viewModel.buttonTapped()
})
_ = self.viewModel.printSomething
.subscribeOn(ConcurrentMainScheduler.instance)
.subscribe(onNext: {
print("[!][\(Thread.current)] -- RxTestViewController.printSomething.onNext -> \($0)")
})
}
}
extension RxTestViewController {
private func setupButton() {
// Add to view
self.view.addSubview(self.button)
// Button config
self.button.setTitle("CLICK ME", for: .normal)
self.button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
// Auto-layout
self.button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
self.button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
self.button.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)])
}
@objc
private func buttonTapped() {
self.viewModel.buttonTapped()
}
}
预期的结果应该是:
[!][<NSThread: 0x600001fee280>{number = 1, name = main}] -- ViewModel.configureWith
[!][<NSThread: 0x600001fee280>{number = 1, name = main}] -- ViewModel.viewDidLoad
[!][<NSThread: 0x600001fee280>{number = 1, name = main}] -- ViewModel.toBePrinted.onNext -> ["First phrase", "Second phrase", "Third phrase"]
[!][<NSThread: 0x600001fee280>{number = 1, name = main}] -- RxTestViewController.toBePrinted.onNext -> ["First phrase", "Second phrase", "Third phrase"]
[!][<NSThread: 0x600001fee280>{number = 1, name = main}] -- ViewModel.buttonTapped
[!][<NSThread: 0x600001fee280>{number = 1, name = main}] -- ViewModel.printSomething.onNext -> ["First phrase", "Second phrase", "Third phrase"]
[!][<NSThread: 0x600001fee280>{number = 1, name = main}] -- RxTestViewController.printSomething.onNext -> ["First phrase", "Second phrase", "Third phrase"]
但是我得到了:
[!][<NSThread: 0x600001fee280>{number = 1, name = main}] -- ViewModel.configureWith
[!][<NSThread: 0x600001fee280>{number = 1, name = main}] -- ViewModel.viewDidLoad
[!][<NSThread: 0x600001fee280>{number = 1, name = main}] -- ViewModel.toBePrinted.onNext -> ["First phrase", "Second phrase", "Third phrase"]
[!][<NSThread: 0x600001fee280>{number = 1, name = main}] -- RxTestViewController.toBePrinted.onNext -> ["First phrase", "Second phrase", "Third phrase"]
[!][<NSThread: 0x600001fee280>{number = 1, name = main}] -- ViewModel.buttonTapped
[!][<NSThread: 0x600001fee280>{number = 1, name = main}] -- ViewModel.printSomething.onNext -> ["First phrase", "Second phrase", "Third phrase"]
如您所见,观察者订阅不会在ViewController 上调用,而只会在ViewModel 上调用。
有趣的是,如果我再次调用 Observable 的 latestFrom 触发函数 (buttonTapped()),ViewModel 订阅和 ViewController 订阅都会按预期调用。
此外,如果我从 configPhrases 可观察链中删除 withLatestFrom 运算符,并将其仅添加到 toBePrinted 可观察链中,则所有工作都按预期进行。
这让我觉得将withLatestFrom 应用到已经应用withLatestFrom 运算符的Observable 是错误的。
【问题讨论】:
-
我宁愿认为线程可能存在问题并且尚未订阅。使用
.debug()运算符来确定是否在您实际订阅RxTestViewController.printSomething之前发生了点击 -
仅供参考,我将您的代码复制并粘贴到一个视图中,并从 ViewController 中展示了您的 VC,它输出了“预期结果”
-
@DanielT。你是通过它的静态 instance() 方法来实例化控制器吗?
-
@Tylerian 是的,我做到了。
标签: swift reactive-programming rx-swift reactivex