简体   繁体   English

使用RxSwift的简单可观察结构?

[英]Simple observable struct with RxSwift?

I'm trying to come up with a simple observable object in Swift and thought to use RxSwift . 我试图在Swift中提出一个简单的可观察对象,并考虑使用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)
    }
  }
}

The above is pure Swift solution for observables from this blog post ; 以上是此博客文章中针对可观察对象的纯Swift解决方案; 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. 因此,我需要观察/订阅更改,而不是实时获取/设置属性。

I keep hearing RxSwift will do just that and more. 我一直听到RxSwift会做到这一点以及更多。 However, I can't find a simple example to match above and beginning to think RxSwift is overkill for my need? 但是,我找不到一个简单的例子来匹配上面并开始认为RxSwift对我的需要是否过度? Thanks for any help. 谢谢你的帮助。

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): 使用RxSwift快速制作这个可观察对象的最简单方法可能是使用RxSwift类变量(这里的所有代码都是未经测试的):

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.

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: 当然有很多方法可以解决这个问题,RxSwifty方法可能是为你的元素序列添加一个扫描操作 ,这与普通数组上的reduce操作非常相似:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM