Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 822
kilik52 Avatar asked Mar 03 '16 08:03

kilik52


1 Answers

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

like image 52
tomahh Avatar answered Nov 20 '22 16:11

tomahh