我是使用 RxSwift 框架的新手,我实际上正在学习并尝试理解基础知识,我希望得到您的一些帮助。
private func observeCurrentIndex() -> Observable<Int> {
return Observable<Int>.create { (observer) -> Disposable in
observer.onNext(self.currentIndex)
return Disposables.create()
}
}
这里我在 currentIndex 上创建了一个 observable,它是一个 int。当我订阅它时,我只得到 currentIndex 的第一个值,即 2。它不应该在 currentIndex 更改时通知我(就像 KVO 那样)吗?
override func viewDidLoad() {
super.viewDidLoad()
observeCurrentIndex()
.subscribe(onNext: { (valeur) in
print("new value \(valeur)")
})
.addDisposableTo(disposeBag)
}
要在每次 currentIndex 更改值时收到通知,我被告知必须为此使用 publishSubject。
@IBAction func increaseAction(_ sender: UIButton) {
if currentIndex <= kMaxIndex {
currentIndex = currentIndex + 1
}
}
有人可以告诉我在哪里以及如何做吗?提前致谢。
最佳答案
通常,Subject
用于将命令式 API 连接到响应式世界。可以找到有关如何使用主题的更多信息 here .
有几个解决方案可以使用 RxSwift 的原语来观察变量的演化
使用 KVO
class WithIndex: NSObject {
dynamic var currentIndex: Int
func observeCurrentIndex() -> Observable<Int> {
return instance.rx.observe(Int.self, "currentIndex")
}
@IBAction func increaseAction(_ sender: UIButton) {
if currentIndex <= kMaxIndex {
currentIndex = currentIndex + 1
}
}
}
此解决方案的缺点是 WithIndex
需要继承 NSObject
才能使 KVO 可用。
使用变量
class WithIndex {
let currentIndex: Variable<Int>
func observeCurrentIndex() -> Observable<Int> {
return currentIndex.asObservable()
}
@IBAction func increaseAction(_ sender: UIButton) {
if currentIndex.value <= kMaxIndex {
currentIndex.value = currentIndex.value + 1
}
}
}
这个比较实用。然后,您可以使用 currentIndex.value = 12
设置 currentIndex
的值,并使用 currentIndex.asObservable().subscribe(...)
进行观察.
变量
is a simple wrapper围绕 BehaviorSubject
并在每次变量值更改时发送一个 .next
事件。
关于swift - 如何使用发布主题来观察变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41849648/