How to observe array property changes in RxSwift

▼魔方 西西 提交于 2019-12-03 13:39:08

Most of the time, if you have control of the backing variable, you would prefer Variable to using rx_observe.

class ViewController: UIViewController {
   var myArray : Variable<NSArray>!
}

The first time you'll use myArray, you would asign it like so

myArray = Variable(["a"])

Then, if you want to change its value

myArray.value = ["b"]

And you can easily observe its changes, using

myArray.asObservable().subscribeNext { value in
  // ...
}

If you really want to use rx_observe (maybe because the variable is used elsewhere in your program and you don't want to change the API of your view controller), you would need to declare myArray as dynamic (another requirement is that the hosting class is a child of NSObject, here UIViewController satisfies this requirement). KVO is not implemented by default in swift, and using dynamic ensures access is done using the objective-c runtime, where KVO events are handled.

class ViewController: UIViewController {
  dynamic var myArray: NSArray!
}

Documentation for this can be found here

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