-
-
Save berkus/f72bd0adccbe26dfb4a4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol ISubscriber { | |
typealias Element | |
func sendNext(e: Element) | |
func sendError(e: NSError) | |
func sendCompleted() | |
} | |
/// Wraps RACSubscriber | |
class Subscriber<T: AnyObject> : ISubscriber { | |
typealias Element = T | |
let subscriber: RACSubscriber | |
init(wrapped: RACSubscriber) { | |
subscriber = wrapped | |
} | |
func sendNext(e: T) | |
{ | |
subscriber.sendNext(e) | |
} | |
func sendError(e: NSError) | |
{ | |
subscriber.sendError(e) | |
} | |
func sendCompleted() | |
{ | |
subscriber.sendCompleted() | |
} | |
} | |
/// Wraps RACSignal | |
class Signal<T: AnyObject> { | |
let signal: RACSignal | |
init(didSubscribe: Subscriber<T> -> ()) | |
{ | |
signal = RACSignal.create({racSubscriber in | |
let subscriber = Subscriber<T>(wrapped: racSubscriber) | |
didSubscribe(subscriber) | |
}) | |
} | |
init(wrapped: RACSignal) | |
{ | |
signal = wrapped | |
} | |
//TODO -[RACSignal return:] could not be called here directly because Swift hates keywords as selectors, hence this suboptimal implementation | |
convenience init(value: T) | |
{ | |
return self.init(didSubscribe: { s in | |
s.sendNext(value) | |
s.sendCompleted() | |
}) | |
} | |
// operations | |
func flatMap<U: AnyObject>(f: T -> Signal<U>) -> Signal<U> | |
{ | |
return Signal<U>(wrapped: signal.flattenMap { value in | |
return f(value as T).signal | |
}) | |
} | |
// subscription | |
func subscribe(next: T -> ()) -> RACDisposable | |
{ | |
return signal.subscribeNext { value in next(value as T) } | |
} | |
func subscribe(next: T -> (), completed: () -> ()) -> RACDisposable | |
{ | |
return signal.subscribeNext( | |
{ value in next(value as T) }, | |
completed: { completed() } | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment