I\'m a Swift and ReactiveCocoa noob at the same time. Using MVVM and Reactive Cocoa v3.0-beta.4 framework, I\'d like to implement this setup, to learn the basics of the new RAC
If you take a look at Colin Eberhardt blog post on ReactiveCocoa 3 there's a very nice approach to this problem.
Basically because it's still in beta there's no extension on UIView
that makes those properties easy to use with RAC3 but you can add them easily. I would recommend adding a UIKit+RAC3.swift
extension and adding them as you need:
import UIKit
import ReactiveCocoa
struct AssociationKey {
static var hidden: UInt8 = 1
static var alpha: UInt8 = 2
static var text: UInt8 = 3
static var enabled: UInt8 = 4
}
func lazyAssociatedProperty(host: AnyObject,
key: UnsafePointer, factory: ()->T) -> T {
var associatedProperty = objc_getAssociatedObject(host, key) as? T
if associatedProperty == nil {
associatedProperty = factory()
objc_setAssociatedObject(host, key, associatedProperty,
UInt(OBJC_ASSOCIATION_RETAIN))
}
return associatedProperty!
}
func lazyMutableProperty(host: AnyObject, key: UnsafePointer,
setter: T -> (), getter: () -> T) -> MutableProperty {
return lazyAssociatedProperty(host, key) {
var property = MutableProperty(getter())
property.producer
.start(next: {
newValue in
setter(newValue)
})
return property
}
}
extension UIView {
public var rac_alpha: MutableProperty {
return lazyMutableProperty(self, &AssociationKey.alpha, { self.alpha = $0 }, { self.alpha })
}
public var rac_hidden: MutableProperty {
return lazyMutableProperty(self, &AssociationKey.hidden, { self.hidden = $0 }, { self.hidden })
}
}
extension UIBarItem {
public var rac_enabled: MutableProperty {
return lazyMutableProperty(self, &AssociationKey.enabled, { self.enabled = $0 }, { self.enabled })
}
}
That way you simply replace the RAC = RACObserve
logic by (for example):
var date = MutableProperty(nil)
var time = MutableProperty(nil)
let doneItem = UIBarButtonItem()
doneItem.rac_enabled <~ date.producer
|> combineLatestWith(time.producer)
|> map { return $0.0 != nil && $0.1 != nil }
Again this is all taken from his blog post which far more descriptive than this answer. I highly recommend anyone interested in using RAC 3 reads his amazing posts and tutorials: