Simple observable struct with RxSwift?

半世苍凉 提交于 2019-12-01 12:47:14

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.

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!