Search code examples
swiftreactive-cocoa

RACObserve doesn't give a value. (Reactive Cocoa with Swift)


dynamic var categories: [Category]?
dynamic var productViewModels: [ProductViewModel]?

var totalCategories = 1

dynamic var currentPage = 0

override init() {
    super.init()

    RACObserve(self, "categories").subscribeNext { [weak self] (x) in
        if let this = self, let categories = x as? [Category] {
            this.totalCategories = categories.count ?? 1 // Why this code doesn't work?
            this.productViewModels = categories.map { ProductViewModel(category: $0.tagName) }
            this.currentPage = 0
        }
    }

    categories = Category.temporaryInitializer()
}

I supposed if x have some value, RACObserve(self, "categories") will work with contain categories's value. But it contains no value. I don't know why x is always nil.

====== Solved problem ======

categories = Category.temporaryInitializer() shouldn't be in init().

I guess RACObserve works fine after init().

But still i don't know why.


Solution

  • According to Apple Documentation

    When you assign a default value to a stored property, or set its initial value within an initializer, the value of that property is set directly, without calling any property observers.

    Reactive observers work on KVO. I guess that is the reason why your observer is not getting called.