Skip to content

Instantly share code, notes, and snippets.

@taufikobet
Forked from dennisfarandy/ReactiveCocoaUtil.swift
Last active August 29, 2015 14:26
Show Gist options
  • Save taufikobet/804571c277e41b4d6ddb to your computer and use it in GitHub Desktop.
Save taufikobet/804571c277e41b4d6ddb to your computer and use it in GitHub Desktop.
some reactivecocoa util that colin eberhardt create, source : https://github.com/ColinEberhardt/ReactiveSwiftFlickrSearch
//
// RACSignal+Extensions.swift
// ReactiveSwiftFlickrSearch
//
// Created by Colin Eberhardt on 15/07/2014.
// Copyright (c) 2014 Colin Eberhardt. All rights reserved.
//
import Foundation
// a collection of extension methods that allows for strongly typed closures
extension RACSignal {
func subscribeNextAs<T>(nextClosure:(T) -> ()) -> () {
self.subscribeNext {
(next: AnyObject!) -> () in
let nextAsT = next as! T
nextClosure(nextAsT)
}
}
func mapAs<T, U>(mapClosure:(T) -> U) -> RACSignal {
return self.map {
(next: AnyObject!) -> AnyObject! in
let nextAsT = next as! T
return mapClosure(nextAsT) as! AnyObject
}
}
func filterAs<T>(filterClosure:(T) -> Bool) -> RACSignal {
return self.filter {
(next: AnyObject!) -> Bool in
let nextAsT = next as! T
return filterClosure(nextAsT)
}
}
func doNextAs<T: AnyObject>(nextClosure:(T) -> ()) -> RACSignal {
return self.doNext {
(next: AnyObject!) -> () in
let nextAsT = next as! T
nextClosure(nextAsT)
}
}
}
class RACSignalEx {
class func combineLatestAs<T, U, R: AnyObject>(signals:[RACSignal], reduce:(T,U) -> R) -> RACSignal {
return RACSignal.combineLatest(signals).mapAs {
(tuple: RACTuple) -> R in
return reduce(tuple.first as! T, tuple.second as! U)
}
}
}
// replaces the RACObserve macro
func RACObserve(target: NSObject!, keyPath: String) -> RACSignal {
return target.rac_valuesForKeyPath(keyPath, observer: target)
}
// a struct that replaces the RAC macro
struct RAC {
var target : NSObject!
var keyPath : String!
var nilValue : AnyObject!
init(_ target: NSObject!, _ keyPath: String, nilValue: AnyObject? = nil) {
self.target = target
self.keyPath = keyPath
self.nilValue = nilValue
}
func assignSignal(signal : RACSignal) {
signal.setKeyPath(self.keyPath, onObject: self.target, nilValue: self.nilValue)
}
}
infix operator ~> { associativity left }
func ~> (signal: RACSignal, rac: RAC) {
rac.assignSignal(signal)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment