subjects playground

This commit is contained in:
Carlos García 2015-07-30 14:43:57 +02:00
parent f79ed3c5fa
commit 5fa8d9e4dd
5 changed files with 89 additions and 0 deletions

View File

@ -0,0 +1,69 @@
import Cocoa
import RxSwift
/*:
To use playgrounds please open Rx.xcworkspace, build RxSwift-OSX scheme and then open playgrounds in Rx.xcworkspace tree view.
*/
func writeSequenceToConsole(name: String, sequence: Observable<String>) {
sequence
>- subscribeNext {
println("Subscription: \(name), value: \($0)")
}
}
/*:
## PublishSubject
PublishSubject can begin emitting items immediately upon creation, but there is a risk that one or more items may be lost between the time the Subject is created and the observer subscribes to it.
*/
example("PublishSubject") {
let subject = PublishSubject<String>()
writeSequenceToConsole("1", subject)
sendNext(subject, "a")
sendNext(subject, "b")
writeSequenceToConsole("2", subject)
sendNext(subject, "c")
sendNext(subject, "d")
}
/*:
## ReplaySubject
ReplaySubject emits to any observer all of the items, in the buffer, that were emitted by the source
*/
example("ReplaySubject") {
let subject = ReplaySubject<String>(bufferSize: 1)
writeSequenceToConsole("1", subject)
sendNext(subject, "a")
sendNext(subject, "b")
writeSequenceToConsole("2", subject)
sendNext(subject, "c")
sendNext(subject, "d")
}
/*:
## BehaviorSubject a.k.a. Variable
ReplaySubject emits to any observer all of the items, in the buffer, that were emitted by the source
*/
example("ReplaySubject") {
let subject = BehaviorSubject(value: "z")
writeSequenceToConsole("1", subject)
sendNext(subject, "a")
sendNext(subject, "b")
writeSequenceToConsole("2", subject)
sendNext(subject, "c")
sendNext(subject, "d")
}

View File

@ -0,0 +1,6 @@
public func example(description: String, action: () -> ()) {
println("\n--- \(description) example ---")
action()
}

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='osx' requires-full-environment='true' display-mode='rendered'>
<timeline fileName='timeline.xctimeline'/>
</playground>

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>

View File

@ -13,6 +13,9 @@
<FileRef
location = "group:Introduction.playground">
</FileRef>
<FileRef
location = "group:Subjects.playground">
</FileRef>
<Group
location = "group:ObservablesOperators"
name = "ObservablesOperators">