简体   繁体   中英

How to observe array property changes in RxSwift

Here is my class:

class ViewController: UIViewController {
   var myArray : NSArray!
} 

I want to fire an event every time myArray points to a new array, like this:

self.myArray = ["a"]

self.myArray = ["b"]

I've tried rx_observe but failed, here is my code:

self.rx_observe(NSArray.self, "myArray").subscribeNext { (array) -> Void in
   print(array)
}

It only fires the first time, what's the problem?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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