ReactiveCocoa rac_valuesForKeyPath not working in Swift

I am trying to adopt ReactiveCocoa in an iOS application written in Swift. Unfortunately, it seems that rac_valuesForKeyPath does not work as expected. Here is an example:

class Source: NSObject { var observable: String = "<Original>" override init() { super.init() dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in self.observable = "<Updated>" println("Updated value to \(self.observable)"); }) } } class Observer: NSObject { init(source: Source) { super.init() source.rac_valuesForKeyPath("observable", observer: self).subscribeNext { (value: AnyObject!) -> Void in println(">>> Observable value changed: \(value)") } } } 

The following output is shown in the example:

 >>> Observable value changed: <Original> Updated value to <Updated> 

This means that the subscribeNext block was not called.

Expected Input:

 >>> Observable value changed: <Original> Updated value to <Updated> >>> Observable value changed: <Updated> 

Which key fix the problem?

+5
source share
1 answer

Observable must be dynamic

I got your sample to work with the following code

 class Source: NSObject { dynamic var string:String = "Initial Value" override init() { super.init() } } class Observer: NSObject { init(source:Source) { super.init() source.rac_valuesForKeyPath("string", observer: self).subscribeNext { (newVal:AnyObject!) -> Void in println(newVal) } } } class ViewController: UIViewController { var source:Source! var obs:Observer! override func viewDidLoad() { super.viewDidLoad() source = Source() obs = Observer(source: source) source.string = "Another Value" } } 
+9
source

Source: https://habr.com/ru/post/1203789/


All Articles