RxSwift的简单可观察结构? [英] Simple observable struct with RxSwift?
问题描述
我正在尝试在Swift中提出一个简单的可观察对象,并考虑使用 RxSwift .我找不到一个简单的例子来做这样的事情:
I'm trying to come up with a simple observable object in Swift and thought to use RxSwift. I couldn't find a simple example to do something like this:
protocol PropertyObservable {
typealias PropertyType
var propertyChanged: Event<(PropertyType, Any)> { get }
}
class Car: PropertyObservable {
typealias PropertyType = CarProperty
let propertyChanged = Event<(CarProperty, Any)>()
dynamic var miles: Int = 0 {
didSet {
propertyChanged.raise(.Miles, oldValue as Any)
}
}
dynamic var name: String = "Turbo" {
didSet {
propertyChanged.raise(.Name, oldValue as Any)
}
}
}
以上是此博客文章中的可观察物的纯Swift解决方案;我真的很喜欢它是基于协议的解决方案,而不是侵入性的.就我而言,我的项目中有一个对象,其中每个属性都在后台(蓝牙设备)异步设置.因此,我需要观察/订阅更改,而不是实时获取/设置属性.
The above is pure Swift solution for observables from this blog post; I really like how it's a protocol-based solution and not invasive. In my case, I have an object in my project where each property is set asynchronously under the hood (bluetooth device). So I need to observe/subscribe to the changes instead of getting/setting the properties in real-time.
我一直听到RxSwift会做到这一点以及更多.但是,我找不到上面匹配的简单示例,并开始认为RxSwift对我的需求而言是过大的?感谢您的帮助.
I keep hearing RxSwift will do just that and more. However, I can't find a simple example to match above and beginning to think RxSwift is overkill for my need? Thanks for any help.
推荐答案
使用RxSwift快速使其可观察的最简单方法可能是使用RxSwift类Variable(此处的所有代码未经测试):
Easiest way to quickly make this observable with RxSwift would probably be to use the RxSwift class Variable (all code here is untested off the top of my head):
import RxSwift
class Car {
var miles = Variable<Int>(0)
var name = Variable<String>("Turbo")
}
这使您可以通过订阅它们来观察值:
This enables you to observe the values by subscribing to them:
let disposeBag = DisposeBag()
let car = Car
car.name.asObservable()
.subscribeNext { name in print("Car name changed to \(name)") }
.addToDisposeBag(disposeBag) // Make sure the subscription disappears at some point.
现在,您在每个事件中都失去了原有的价值.当然,有很多方法可以解决此问题,RxSwifty方法可能是向您的计算机添加扫描操作元素序列,其作用与reduce对普通数组的作用类似:
Now you've lost the old value in each event. There are of course numerous ways to solve this, the RxSwifty way would probably be to add a scan operation to your element sequence, which works a lot like reduce does on a normal Array:
car.name.asObservable()
.scan(seed: ("", car.name.value)) { (lastEvent, newElement) in
let (_, oldElement) = lastEvent
return (oldElement, newElement)
}
.subscribeNext { (old, new) in print("Car name changed from \(old) to \(new)") }
.addToDisposeBag(disposeBag)
这篇关于RxSwift的简单可观察结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!