FRP in Swift.
From a value.
lets:Stream<String>=.pure("foo")
s.subscrible{(e:Packet<String>)iniflet o = e.value {println(o)} // ==> "foo"
}From multiple values.
lets:Stream<Int>=.list([2,3,5])
s.subscrible{(e:Packet<Int>)iniflet o = e.value {println(o)} // ==> 2, 3, 5 (in repetition)
}Stream<>#map - receiving/transforming respectively the values of a stream with no effect to the stream itself
leta:Stream<String>=.args("ObjC","Swift")letb:Stream<Double>= a.map{ $0.utf16Count *2.0}
b.subscribe{(e:Packet<Double>)iniflet o = e.value {println(o)} // ==> 8, 10 (in repetition)
}lets:Stream<String>=.list(["f o o","b a r"])
s.flatMap{(e:Packet<String>)in.list(e.componentsSeparatedByString(""))}.subscribe{(e:Packet<String>)iniflet o = e.value {println(o)} // ==> "f", "o", "o", "b", "a", "r"
}leta:Stream<String>=.pure("foo")letb:Stream<String>=.list("bar")letc:Stream<String>=mix([a, b])
c.subscribe{(e:Packet<String>)iniflet o = e.value {println(o)}
// ==> "foo", "bar" or "bar", "foo" (nondeterministic)
}// The definition of a typical observer class
classMyButtonListener:ButtonListener{letsubject=Subject<ButtonEvent?>(nil)func onButtonClick(e:ButtonEvent){
subject.value = e
}}letobserver:MyButtonListener= /* ... */
observer.subject.unwrap.subscribe{(e:Packet<ButtonEvent?>)in
/* ... */
}Streams.range(0...9).parMap{ e inNSThread.sleepForTimeInterval(3)return e * e * e
}.fold(0){ $0 + $1 }.subscribe{e: Packet<Int>iniflet o = e.value {println(o)} // ==> 2025 (in about 3 seconds)
}For more practices, the following link(s) can be helpful.
| Type | Description |
|---|---|
Packet<A> | An event. |
Stream<A> | An event-stream. |
Channel<A> | A subscription used for both receiving events and closing the corresponding event-stream. |
Subject<A> | blah blah blah. |
Streams | A mere namespace(as a set of class methods) that contains a lot of useful combinators. |
0.0.1 (^_^;)
MIT