Skip to content

Repository files navigation

ReactiveSwift

FRP in Swift.

Sample Code

Creating a stream from the immediate values.

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)
}

Combinators

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)
}
Stream<>#flatMap - it works similarly to map but also affects the behavior of the resulted stream
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"
}
mix - interleaves the given streams(of the same type) to one stream
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)
}

Replaces an unregulated "event" handing by the (FRP style) event-stream.

// 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
/* ... */
}

Multithreading

Map-Reduce like operation
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.

The Most Important Classes (and Types)

TypeDescription
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.
StreamsA mere namespace(as a set of class methods) that contains a lot of useful combinators.

Version

0.0.1 (^_^;)

License

MIT

About

FRP in Swift

Resources

Stars

17 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages