如何使用ReactiveCocoa观察Swift中的属性发生了变化

Rob*_*ang 0 reactive-cocoa swift reactive-swift swift4

我正在使用新的ReactiveCocoa + ReactiveSwift编写Swift.我正在尝试使用新的ReactiveCocoa框架执行以下操作(在ReactiveCocoa 2.5中):

[[RACObserve(user, username) skip:1] subscribeNext:^(NSString *newUserName) {
    // perform actions...
}];
Run Code Online (Sandbox Code Playgroud)

经过一些研究,我仍然无法弄清楚如何做到这一点.请帮忙!非常感谢你!

MeX*_*eXx 12

您的代码片段通过KVO工作,这仍然可以使用Swift中最新的RAC/RAS,但不再是推荐的方式了.

使用财产

推荐的方法是使用Property哪个值保存并且可以观察到.

这是一个例子:

struct User {
  let username: MutableProperty<String>
  init(name: String) {
    username = MutableProperty(name)
  }
}

let user = User(name: "Jack")

// Observe the name, will fire once immediately with the current name
user.username.producer.startWithValues { print("User's name is \($0)")}
// Observe only changes to the value, will not fire with the current name
user.username.signal.observeValues { print("User's new name is \($0)")}

user.username.value = "Joe"
Run Code Online (Sandbox Code Playgroud)

这将打印

用户名是杰克

用户名是Joe

用户的新名字是Joe

使用KVO

如果由于某种原因你仍然需要使用KVO,那么你将如何做到这一点.请记住,KVO仅适用于显式子类NSObject,如果该类是用Swift编写的,则该属性需要使用@objc 注释dynamic!

class NSUser: NSObject {
  @objc dynamic var username: String
  init(name: String) {
    username = name
    super.init()
  }
}

let nsUser = NSUser(name: "Jack")

// KVO the name, will fire once immediately with the current name
nsUser.reactive.producer(forKeyPath: "username").startWithValues { print("User's name is \($0)")}
// KVO only changes to the value, will not fire with the current name
nsUser.reactive.signal(forKeyPath: "username").observeValues { print("User's new name is \($0)")}

nsUser.username = "Joe"
Run Code Online (Sandbox Code Playgroud)

这将打印

用户名是可选的(杰克)

用户的新名称是Optional(Joe)

用户名是可选的(Joe)