如何在RxSwift中观察数组属性的变化 [英] How to observe array property changes in RxSwift

查看:1717
本文介绍了如何在RxSwift中观察数组属性的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的课程:

class ViewController: UIViewController {
   var myArray : NSArray!
} 

我想每次myArray指向新数组时都触发一个事件,如下所示:

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

self.myArray = ["a"]

self.myArray = ["b"]

我尝试过rx_observe但失败了,这是我的代码:

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?

推荐答案

在大多数情况下,如果可以控制后备变量,则宁可Variable也不愿意使用rx_observe.

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>!
}

第一次使用myArray时,您将像这样进行分配

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
  // ...
}


如果您确实要使用rx_observe(可能是因为该变量在程序的其他位置使用并且您不想更改视图控制器的API),则需要将myArray声明为(另一个要求是托管类是NSObject的子级,此处UIViewController满足此要求).默认情况下,不会快速实现KVO,使用动态功能可确保通过Objective-C运行时完成访问,并在该运行时中处理KVO事件.


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

这篇关于如何在RxSwift中观察数组属性的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆