Xcode 7 version of playground

This commit is contained in:
Carlos García 2015-08-19 19:05:09 +02:00
parent 4ea534ba1e
commit 734508fd81
40 changed files with 467 additions and 515 deletions

View File

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

View File

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

View File

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:../../Projects/OSXPlayground.playground">
</FileRef>
</Workspace>

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Timeline
version = "3.0">
<TimelineItems>
</TimelineItems>
</Timeline>

View File

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

View File

@ -1,4 +0,0 @@
<?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

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

View File

@ -1,4 +0,0 @@
<?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

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

View File

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

View File

@ -1,4 +0,0 @@
<?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

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

View File

@ -1,4 +0,0 @@
<?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

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

View File

@ -1,4 +0,0 @@
<?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

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

View File

@ -1,4 +0,0 @@
<?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

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

View File

@ -1,4 +0,0 @@
<?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

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Timeline
version = "3.0">
<TimelineItems>
</TimelineItems>
</Timeline>

View File

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

View File

@ -1,4 +0,0 @@
<?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

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

View File

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

View File

@ -10,47 +10,9 @@
<FileRef
location = "group:CHANGELOG.md">
</FileRef>
<Group
location = "group:Playgrounds"
name = "Playgrounds">
<FileRef
location = "group:Introduction.playground">
</FileRef>
<FileRef
location = "group:Subjects.playground">
</FileRef>
<Group
location = "group:ObservablesOperators"
name = "ObservablesOperators">
<FileRef
location = "group:Observables+Creating.playground">
</FileRef>
<FileRef
location = "group:Observables+Transforming.playground">
</FileRef>
<FileRef
location = "group:Observables+Filtering.playground">
</FileRef>
<FileRef
location = "group:Observables+Combining.playground">
</FileRef>
<FileRef
location = "group:Observables+Error Handling.playground">
</FileRef>
<FileRef
location = "group:Observables+Utility.playground">
</FileRef>
<FileRef
location = "group:Observables+Conditional and Boolean.playground">
</FileRef>
<FileRef
location = "group:Observables+Mathematical and Aggregate.playground">
</FileRef>
<FileRef
location = "group:Observables+Connectable.playground">
</FileRef>
</Group>
</Group>
<FileRef
location = "group:RxSamples.playground">
</FileRef>
<FileRef
location = "group:RxSwift/RxSwift.xcodeproj">
</FileRef>

View File

@ -1,24 +1,23 @@
import Cocoa
//: [<< Previous](@previous) - [Index](Index)
import RxSwift
/*:
# To use playgrounds please open `Rx.xcworkspace`, build `RxSwift-OSX` scheme and then open playgrounds in `Rx.xcworkspace` tree view.
*/
/*:
## Combination operators
Operators that work with multiple source Observables to create a single Observable.
### `startWith`
Return an observeble which emits a specified item before emitting the items from the source Observable.
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/startwith.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/startwith.html )
*/
example("startWith") {
let aggregateSubscriber = from([4, 5, 6, 7, 8, 9])
.startWith(3)
.startWith(2)
@ -26,74 +25,76 @@ example("startWith") {
.startWith(0)
.subscribeNext { int in
print(int)
}
}
}
e/*:
/*:
### `combineLatest`
Takes several source Obserbables and a closure as parameters, returns an Observable which emits the latest items of each source Obsevable, procesed through the closure.
Once each source Observables have each emitted an item, `combineLatest` emits an item every time either source Observable emits an item.
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/combinelatest.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/combinelatest.html )
The next example shows how
The next example shows how
*/
xample("combineLatest 1st") {
example("combineLatest 1st") {
let intOb1 = PublishSubject<String>()
let intOb2 = PublishSubject<Int>()
combineLatest(intOb1, intOb2) {
"\($0) \($1)"
}
.subscribeNext {
print($0)
}
}
print("send A to first channel")
sendNext(intOb1, "A")
print("note that nothing outputs")
print("\nsend 1 to second channel")
sendNext(intOb2, 1)
print("now that there is something in both channels, there is output")
print("\nsend B to first channel")
sendNext(intOb1, "B")
print("now that both channels are full, whenever either channel emits a value, the combined channel also emits a value")
print("\nsend 2 to second channel")
sendNext(intOb2, 2)
print("note that the combined channel emits a value whenever either sub-channel emits a value, even if the value is the same")
}
example("combineLat//: This example show once in each channel there are output for each new channel output the resulting observable also produces an output
est 2nd") {
//: This example show once in each channel there are output for each new channel output the resulting observable also produces an output
example("combineLatest 2nd") {
let intOb1 = just(2)
let intOb2 = from([0, 1, 2, 3, 4])
combineLatest(intOb1, intOb2) {
$0 * $1
$0 * $1
}
.subscribeNext {
print($0)
}
}
}
example("combineLates/*:
/*:
There are a serie of functions `combineLatest`, they take from two to ten sources Obserbables and the closure
The next sample shows combineLatest called with three sorce Observables
*/
t 3rd") {
example("combineLatest 3rd") {
let intOb1 = just(2)
let intOb2 = from([0, 1, 2, 3])
let intOb3 = from([0, 1, 2, 3, 4])
combineLatest(intOb1, intOb2, intOb3) {
($0 + $1) * $2
}
@ -103,98 +104,102 @@ t 3rd") {
}
example("zip 1st") {
/*:
/*:
### `zip`
Takes several source Observables and a closure as parameters, returns an Observable which emit the items of the second Obsevable procesed, through the closure, with the last item of first Observable
The Observable returned by `zip` emits an item only when all of the imputs Observables have emited an item
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/zip.png)
[More info in reactive.io website](http://reactivex.io/documentation/operators/zip.html)
*/
let intOb1 = PublishSubject<String>()
example("zip 1st") {
let intOb1 = PublishSubject<String>()
let intOb2 = PublishSubject<Int>()
zip(intOb1, intOb2) {
"\($0) \($1)"
}
.subscribeNext {
print($0)
}
}
print("send A to first channel")
sendNext(intOb1, "A")
print("note that nothing outputs")
print("\nsend 1 to second channel")
sendNext(intOb2, 1)
print("now that both source channels have output, there is output")
print("\nsend B to first channel")
sendNext(intOb1, "B")
print("note that nothing outputs, since channel 1 has two outputs but channel 2 only has one")
print("\nsend C to first channel")
sendNext(intOb1, "C")
print("note that nothing outputs, it is the same as in the previous step, since channel 1 has three outputs but channel 2 only has one")
print("\nsend 2 to second channel")
sendNext(intOb2, 2)
print("note that the combined channel emits a value with the second output of each channel")
}
//: This example show once in each channel there are output for each new channel output the resulting observable also produces an output
example("zip 2nd") {
let intOb1 = just(2)//: This example show once in each channel there are output for each new channel output the resulting observable also produces an output
let intOb1 = just(2)
let intOb2 = from([0, 1, 2, 3, 4])
zip(intOb1, intOb2) {
$0 * $1
$0 * $1
}
.subscribeNext {
print($0)
}
}
}
example("zip 3rd") {
let intOb1 = from([0, /*:
There are a serie of functions `zip`, they take from two to ten sources Obserbables and the closure
The next sample shows zip called with three sorce Observables
*/
1])
There are a serie of functions `zip`, they take from two to ten sources Obserbables and the closure
The next sample shows zip called with three sorce Observables
*/
1])
let intOb2 = from([0, 1, 2, 3])
let intOb3 = from([0, 1, 2, 3, 4])
zip(intOb1, intOb2, intOb3) {
($0 + $1) * $2
}
.subscribeNext {
print($0)
}
}
}
example("merge 1st") {
let subject1 = Publish/*:
/*:
### `merge`
Combine multiple Observables, of the same type, into one by merging their emissions
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/merge.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/merge.html )
*/
Subject<Int>()
example("merge 1st") {
let subject1 = PublishSubject<Int>()
let subject2 = PublishSubject<Int>()
merge(sequence(subject1, subject2))
sequence(subject1, subject2)
.merge
.subscribeNext { int in
print(int)
}
}
sendNext(subject1, 20)
sendNext(subject1, 40)
sendNext(subject1, 60)
@ -208,13 +213,13 @@ Subject<Int>()
example("merge 2nd") {
let subject1 = PublishSubject<Int>()
let subject2 = PublishSubject<Int>()
sequence(subject1, subject2)
sequence(subject1, subject2)
.merge(maxConcurrent: 2)
.subscribeNext { int in
print(int)
}
sendNext(subject1, 20)
sendNext(subject1, 40)
sendNext(subject1, 60)
@ -226,40 +231,47 @@ example("merge 2nd") {
example("switchLatest") {
let var1 = Variable(0)/*:
/*:
### `switchLatest`
Convert an Observable that emits Observables into a single Observable that emits the items emitted by the most-recently-emitted of those Observables.
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/switch.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/switch.html )
*/
example("switchLatest") {
let var1 = Variable(0)
let var2 = Variable(200)
// var3 is like an Observable<Observable<Int>>
let var3 = Variable(var1 as Observable<Int>)
let d = var3
.switchLatest
.subscribeNext { (e: Int) -> Void in
print("\(e)")
}
var1.sendNext(1)
var1.sendNext(2)
var1.sendNext(3)
var1.sendNext(4)
var3.sendNext(var2)
var2.sendNext(201)
print("Note which no listen to var1")
var1.sendNext(5)
var1.sendNext(6)
var1.sendNext(7)
sendCompleted(var1)
var2.sendNext(202)
var2.send
var2.sendNext(203)
var2.sendNext(204)
}
//: [Index](Index) - [Next >>](@next)

View File

@ -1,9 +1,8 @@
//: [<< Previous](@previous) - [Index](Index)
import Cocoa
import RxSwift
/*:
# To use playgrounds please open `Rx.xcworkspace`, build `RxSwift-OSX` scheme and then open playgrounds in `Rx.xcworkspace` tree view.
*/
/*:
## Conditional and Boolean Operators
@ -13,44 +12,46 @@ Operators that evaluate one or more Observables or items emitted by Observables.
### `takeUntil`
Discard any items emitted by an Observable after a second Observable emits an item or terminates.
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/takeuntil.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/takeuntil.html )
*/
example("takeUntil") {
let observable1 = PublishSubject<Int>()
let observable2 = PublishSubject<Int>()
observable1
.takeUntil(observable2)
.subscribeNext { int in
print(int)
}
sendNext(observable1, 1)
sendNext(observable1, 2)
sendNext(observable1, 3)
sendNext(observable1, 4)
sendNext(observable2, 1)
sendNext(observable1, 5)
}
e/*:
/*:
### `takeWhile`
Mirror items emitted by an Observable until a specified condition becomes false
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/takewhile.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/takewhile.html )
*/
xample("takeWhile") {
example("takeWhile") {
let observable1 = PublishSubject<Int>()
observable1
.takeWhile { int in
int < 4
@ -58,12 +59,14 @@ xample("takeWhile") {
.subscribeNext { int in
print(int)
}
sendNext(observable1, 1)
sendNext(observable1, 2)
sendNext(observable1, 3)
sendNext(observable1, 4)
sendNext(observable1, 5)
}
//: [Index](Index) - [Next >>](@next)

View File

@ -1,10 +1,8 @@
import Cocoa
//: [<< Previous](@previous) - [Index](Index)
import RxSwift
import XCPlayground
/*:
# To use playgrounds please open `Rx.xcworkspace`, build `RxSwift-OSX` scheme and then open playgrounds in `Rx.xcworkspace` tree view.
*/
/*:
## Connectable Observable Operators
@ -14,52 +12,55 @@ Specialty Observables that have more precisely-controlled subscription dynamics.
*/
func sampleWithoutConnectableOperators() {
let int1 = interval(1, MainScheduler.sharedInstance)
int1
.subscribeNext {
print("first subscription \($0)")
}
}
delay(5) {
int1
.subscribeNext {
print("second subscription \($0)")
}
}
}
sampleWithoutConnectableOperators()
//sampleWithoutConnectableOperators()
fu/*:
/*:
### `multicast`
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/publishconnect.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/publish.html )
*/
nc sampleWithMulticast() {
func sampleWithMulticast() {
let subject1 = PublishSubject<Int64>()
subject1
.subscribeNext {
print("Subject \($0)")
}
}
let int1 = interval(1, MainScheduler.sharedInstance)
.multicast(subject1)
int1
.subscribeNext {
print("first subscription \($0)")
}
delay(2) {
int1.connect()
}
delay(4) {
int1
.subscribeNext {
@ -67,14 +68,14 @@ nc sampleWithMulticast() {
print("---")
}
}
delay(6) {
int1
.subscribeNext {
print("thirth subscription \($0)")
}
}
}
//sampleWithMulticast()
@ -83,29 +84,30 @@ nc sampleWithMulticast() {
func sampleW/*:
/*:
### `replay`
Ensure that all observers see the same sequence of emitted items, even if they subscribe after the Observable has begun emitting items.
publish = multicast + replay subject
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/replay.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/replay.html )
*/
ithReplayBuffer0() {
func sampleWithReplayBuffer0() {
let int1 = interval(1, MainScheduler.sharedInstance)
.replay(0)
int1
.subscribeNext {
print("first subscription \($0)")
}
}
delay(2) {
int1.connect()
}
delay(4) {
int1
.subscribeNext {
@ -113,50 +115,50 @@ ithReplayBuffer0() {
print("---")
}
}
delay(6) {
int1
.subscribeNext {
print("thirth subscription \($0)")
}
}
}
//sampleWithReplayBuffer0()
func sampleWithReplayBuffer2() {
print("--- sampleWithReplayBuffer2 ---\n")
let int1 = interval(1, MainScheduler.sharedInstance)
.replay(2)
int1
.subscribeNext {
print("first subscription \($0)")
}
}
delay(2) {
int1.connect()
}
delay(4) {
int1
.subscribeNext {
print("second subscription \($0)")
print("---")
}
}
}
delay(6) {
int1
.subscribeNext {
print("third subscription \($0)")
}
}
}
}
//sampleWithReplayBuffer2()
@ -165,8 +167,7 @@ func sampleWithReplayBuffer2() {
func sampleWithPublish() {
/*:
/*:
### `publish`
Convert an ordinary Observable into a connectable Observable.
@ -176,19 +177,20 @@ so publish is basically replay(0)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/publish.html )
*/
func sampleWithPublish() {
let int1 = interval(1, MainScheduler.sharedInstance)
.publish
int1
.subscribeNext {
print("first subscription \($0)")
}
}
delay(2) {
int1.connect()
}
delay(4) {
int1
.subscribeNext {
@ -196,14 +198,14 @@ so publish is basically replay(0)
print("---")
}
}
delay(6) {
int1
.subscribeNext {
print("third subscription \($0)")
}
}
}
//sampleWithPublish()
@ -214,13 +216,17 @@ so publish is basically replay(0)
XCPSetExecutionShouldContinueIndefi/*:
/*:
### `refCount`
Make a Connectable Observable behave like an ordinary Observable.
[More info in reactive.io website]( http://reactivex.io/documentation/operators/refcount.html )
*/
nit/*:
/*:
### `Variable` / `sharedWithCachedLastResult`
*/
ely(continueIndefinitely: true)
XCPSetExecutionShouldContinueIndefinitely(true)
//: [Index](Index)

View File

@ -1,9 +1,6 @@
import Cocoa
import RxSwift
//: [<< Previous](@previous) - [Index](Index)
/*:
# To use playgrounds please open `Rx.xcworkspace`, build `RxSwift-OSX` scheme and then open playgrounds in `Rx.xcworkspace` tree view.
*/
import RxSwift
/*:
## Creating observables
@ -14,11 +11,15 @@ Operators that originate new Observables.
### `empty`
Creates an observable that contains no objects. The only message it sends is the `.Completed` message.
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/empty.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/empty-never-throw.html )
*/
example("Empty observable") {
let emptyObservable: Observable<Int> = empty()
let emptySubscriber = emptyObservable .subscribe { event in
switch event {
case .Next(let box):
@ -31,7 +32,7 @@ example("Empty observable") {
}
}
exampl/*:
/*:
As you can see, no values are ever sent to the subscriber of an empty observable. It just completes and is done.
@ -39,31 +40,37 @@ As you can see, no values are ever sent to the subscriber of an empty observable
### `never`
Creates an observable that contains no objects and never completes or errors out.
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/never.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/empty-never-throw.html )
*/
e("Never observable") {
example("Never observable") {
let neverObservable: Observable<String> = never()
let neverSubscriber = neverObservable
let neverSubscriber = neverObservable
.subscribe { _ in
print("This block is never called.")
}
}
}
example/*:
### `failWith`
/*:
### `failWith` a.k.a `throw`
Creates an observable that contains no objects and send only a error out.
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/throw.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/empty-never-throw.html )
*/
("failWith") {
example("failWith") {
let error = NSError(domain: "Test", code: -1, userInfo: nil)
let errorObservable: Observable<Int> = failWith(error)
let errorSubscriber = errorObservable
let errorSubscriber = errorObservable
.subscribe { event in
switch event {
case .Next(let box):
@ -73,19 +80,22 @@ Creates an observable that contains no objects and send only a error out.
case .Error(let error):
print("\(error)")
}
}
}
}
example("retu/*:
/*:
### `returnElement` / `just`
These two functions behave identically. They send two messages to subscribers. The first message is the value and the second message is `.Complete`.
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/just.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/just.html )
*/
rnElement/just") {
example("returnElement/just") {
let oneObservable = just(32)
let oneObservableSubscriber = oneObservable
.subscribe { event in
switch event {
@ -100,7 +110,7 @@ rnElement/just") {
}
example("returnElem/*:
/*:
Here we see that the `.Next` event is sent just once, then the `.Completed` event is sent.
@ -109,9 +119,9 @@ Here we see that the `.Next` event is sent just once, then the `.Completed` even
Now we are getting to some more interesting ways to create an Observable. This function creates an observable that produces a number of values before completing.
*/
ents") {
example("sequence") {
let multipleObservable/* : Observable<Int> */ = sequence(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
let multipleObservableSubscriber = multipleObservable
.subscribe { event in
switch event {
@ -122,22 +132,25 @@ ents") {
case .Error(let error):
print("\(error)")
}
}
}
}
example("from") {
let/*:
/*:
With the above, you will see that the `.Next` event was sent ten times, once for each element. Then `.Complete` was sent.
### `from`
We can also create an observable from any SequenceType, such as an array
We can also create an observable from any SequenceType, such as an array.
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/from.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/from.html )
*/
fromArrayObservable = from([1, 2, 3, 4, 5])
example("from") {
let fromArrayObservable = from([1, 2, 3, 4, 5])
let fromArrayObservableSubscriber = fromArrayObservable
.subscribe { event in
switch event {
@ -148,65 +161,69 @@ We can also create an observable from any SequenceType, such as an array
case .Error(let error):
print("\(error)")
}
}
}
}
example("create") {
pr/*:
/*:
### `create`
Create an Observable from scratch by means of a function
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/create.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/create.html )
*/
int("creating")
example("create") {
print("creating")
let observable: Observable<Int> = create { observer in
print("emmiting")
sendNext(observer, 0)
sendNext(observer, 1)
sendNext(observer, 2)
return AnonymousDisposable {}
}
observable
.subscribeNext {
print($0)
}
observable
.subscribeNext {
print($0)
}
}
example("defer") {
let defered/*:
/*:
### `defer`
Create an Observable from a function which create an observable. But do not create the Observable until the observer subscribes, and create a fresh Observable for each observer
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/defer.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/defer.html )
*/
: Observable<Int> = defer {
example("deferred") {
let defered: Observable<Int> = deferred {
print("creating")
return create { observer in
print("emmiting")
sendNext(observer, 0)
sendNext(observer, 1)
sendNext(observer, 2)
return AnonymousDisposable {}
}
}
defered
.subscribeNext {
print($0)
}
defered
.subscribeNext {
print($0)
@ -214,3 +231,6 @@ Create an Observable from a function which create an observable. But do not crea
}
//: [Index](Index) - [Next >>](@next)

View File

@ -1,9 +1,7 @@
import Cocoa
//: [<< Previous](@previous) - [Index](Index)
import RxSwift
/*:
# To use playgrounds please open `Rx.xcworkspace`, build `RxSwift-OSX` scheme and then open playgrounds in `Rx.xcworkspace` tree view.
*/
/*:
## Error Handling Operators
@ -11,85 +9,82 @@ Operators that help to recover from error notifications from an Observable.
*/
/*:
### `catch`
### `catchError`
Recover from an onError notification by continuing the sequence without error
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/catch.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/catch.html )
*/
example("catch 1st") {
example("catchError 1st") {
let observable1 = PublishSubject<Int>()
let observable2 = PublishSubject<Int>()
observable1
.catch { error in
.catchError { error in
return observable2
}
.subscribe { event in
switch event {
case .Next(let box):
print("\(box.value)")
case .Next(let value):
print("\(value)")
case .Completed:
print("completed")
case .Error(let error):
print("\(error)")
}
}
}
sendNext(observable1, 1)
sendNext(observable1, 2)
sendNext(observable1, 3)
sendNext(observable1, 4)
sendError(observable1, NSError(domain: "Test", code: 0, userInfo: nil))
sendNext(observable2, 100)
sendNext(observable2, 200)
sendNext(observable2, 300)
sendNext(observable2, 400)
sendCompleted(observable2)
}
example("catch 2nd") {
example("catchError 2nd") {
let observable1 = PublishSubject<Int>()
observable1
.catch(100)
.catchError(100)
.subscribe { event in
switch event {
case .Next(let box):
print("\(box.value)")
case .Next(let value):
print("\(value)")
case .Completed:
print("completed")
case .Error(let error):
print("\(error)")
}
}
}
sendNext(observable1, 1)
sendNext(observable1, 2)
sendNext(observable1, 3)
sendNext(observable1, 4)
sendError(observable1, NSError(domain: "Test", code: 0, userInfo: nil))
}
example("re/*:
/*:
### `retry`
If a source Observable emits an error, resubscribe to it in the hopes that it will complete without error
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/retry.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/retry.html )
*/
try") {
example("retry") {
var count = 1 // bad practice, only for example purposes
let observable: Observable<Int> = create { observer in
let error = NSError(domain: "Test", code: 0, userInfo: nil)
@ -104,20 +99,23 @@ try") {
sendNext(observer, 4)
sendNext(observer, 5)
sendCompleted(observer)
return AnonymousDisposable {}
}
observable
.retry
.subscribe { event in
switch event {
case .Next(let box):
print("\(box.value)")
case .Next(let value):
print("\(value)")
case .Completed:
print("completed")
case .Error(let error):
print("\(error)")
}
}
}
}
//: [Index](Index) - [Next >>](@next)

View File

@ -1,9 +1,7 @@
import Cocoa
//: [<< Previous](@previous) - [Index](Index)
import RxSwift
/*:
# To use playgrounds please open `Rx.xcworkspace`, build `RxSwift-OSX` scheme and then open playgrounds in `Rx.xcworkspace` tree view.
*/
/*:
## Filtering Observables
@ -13,7 +11,10 @@ Operators that selectively emit items from a source Observable.
### `where` / `filter`
emit only those items from an Observable that pass a predicate test
Emit only those items from an Observable that pass a predicate test
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/filter.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/filter.html )
*/
@ -24,36 +25,45 @@ example("filter") {
}
.subscribeNext { value in
print("\(value)")
}
}
}
e/*:
/*:
### `distinctUntilChanged`
suppress duplicate items emitted by an Observable
Suppress duplicate items emitted by an Observable
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/distinct.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/distinct.html )
*/
xample("distinctUntilChanged") {
example("distinctUntilChanged") {
let distinctUntilChangedSubscriber = sequence(1, 2, 3, 1, 1, 4)
.distinctUntilChanged
.distinctUntilChanged()
.subscribeNext { value in
print("\(value)")
}
}
}
exa/*:
/*:
### `take`
Emit only the first n items emitted by an Observable
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/take.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/take.html )
*/
mple("take") {
example("take") {
let distinctUntilChangedSubscriber = sequence(1, 2, 3, 4, 5, 6)
.take(3)
.subscribeNext { value in
print("\(value)")
}
}
}
//: [Index](Index) - [Next >>](@next)

View File

@ -0,0 +1,28 @@
/*:
> # IMPORTANT: To use `RxSamples`, please:
1. Open `Rx.xcworkspace`
2. Build `RxSwift-OSX` scheme
3. And then open `RxSamples` in `Rx.xcworkspace` tree view.
4. View the console to view log strings. Choose `View > Show Debug Area`
*/
/*:
## Index:
1. [Introduction](Introduction)
2. [Subjects](Subjects)
3. [Creating observables](Creating_observables)
4. [Transforming Observables](Transforming_Observables)
5. [Filtering Observables](Filtering_Observables)
6. [Combining Observables](Combining_Observables)
7. [Error Handling Operators](Error_Handling_Operators)
8. [Observable Utility Operators](Observable_Utility_Operators)
9. [Conditional and Boolean Operators](Conditional_and_Boolean_Operators)
10. [Mathematical and Aggregate Operators](Mathematical_and_Aggregate_Operators)
11. [Connectable Observable Operators](Connectable_Observable_Operators)
*/
//: [Index](Index) - [Next >>](@next)

View File

@ -1,12 +1,12 @@
import Cocoa
//: [<< Index](@previous)
import RxSwift
/*:
# To use playgrounds please open `Rx.xcworkspace`, build `RxSwift-OSX` scheme and then open playgrounds in `Rx.xcworkspace` tree view.
*/
# Introduction
/*:
## Why use RxSwift?
A vast majority of the code we write revolves around responding to external actions. When a user manipulates a control, we need to write an @IBAction to respond to that. We need to observe Notifications to detect when the keyboard changes position. We must provide blocks to execute when URL Sessions respond with data. And we use KVO to detect changes in variables.
All of these various systems makes our code needlessly complex. Wouldn't it be better if there was one consistent system that handled all of our call/response code? Rx is such a system.
@ -25,7 +25,7 @@ Creating an Observable is one thing, but if nothing subscribes to the observable
example("Empty observable") {
let emptyObservable: Observable<Int> = empty()
let emptySubscriber = emptyObservable .subscribe { event in
switch event {
case .Next(let box):
@ -38,6 +38,8 @@ example("Empty observable") {
}
}
/*:
As you can see, no values are ever sent to the subscriber of an empty observable. It just completes and is done.
*/
@ -49,7 +51,7 @@ As you can see, no values are ever sent to the subscriber of an empty observable
example("Never observable") {
let neverObservable: Observable<String> = never()
let neverSubscriber = neverObservable .subscribe { _ in
print("This block is never called.")
}
@ -62,7 +64,7 @@ These two functions behave identically. They send two messages to subscribers. T
example("returnElement/just") {
let oneObservable = just(32)
let oneObservableSubscriber = oneObservable
.subscribe { event in
switch event {
@ -87,7 +89,7 @@ Now we are getting to some more interesting ways to create an Observable. This f
example("sequence") {
let multipleObservable/* : Observable<Int> */ = sequence(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
let multipleObservableSubscriber = multipleObservable
.subscribe { event in
switch event {
@ -97,8 +99,8 @@ example("sequence") {
print("completed")
case .Error(let error):
print("\(error)")
}
}
}
}
/*:
@ -112,7 +114,7 @@ We can also create an observable from any SequenceType, such as an array
example("from") {
let fromArrayObservable = from([1, 2, 3, 4, 5])
let fromArrayObservableSubscriber = fromArrayObservable
.subscribe { event in
switch event {
@ -122,8 +124,8 @@ example("from") {
print("completed")
case .Error(let error):
print("\(error)")
}
}
}
}
/*:
@ -201,9 +203,7 @@ example("aggregate") {
.aggregate(0, +)
.subscribeNext { value in
print("\(value)")
}
}
}
/*:
To be continued...
*/
//: [Index](Index) - [Next >>](@next)

View File

@ -1,9 +1,7 @@
import Cocoa
//: [<< Previous](@previous) - [Index](Index)
import RxSwift
/*:
# To use playgrounds please open `Rx.xcworkspace`, build `RxSwift-OSX` scheme and then open playgrounds in `Rx.xcworkspace` tree view.
*/
/*:
## Mathematical and Aggregate Operators
@ -14,53 +12,65 @@ Operators that operate on the entire sequence of items emitted by an Observable
### `concat`
Emit the emissions from two or more Observables without interleaving them.
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/concat.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/concat.html )
*/
example("concat") {
let var1 = Variable(0)
let var2 = Variable(200)
// var3 is like an Observable<Observable<Int>>
let var3 = Variable(var1 as Observable<Int>)
let d = var3
.concat
.subscribeNext { (e: Int) -> Void in
print("\(e)")
}
}
var1.sendNext(1)
var1.sendNext(2)
var1.sendNext(3)
var1.sendNext(4)
var3.sendNext(var2)
var2.sendNext(201)
var1.sendNext(5)
var1.sendNext(6)
var1.sendNext(7)
sendCompleted(var1)
var2.sendNext(202)
var2.sendNext(203)
var2.sendNext(204)
}
e/*:
/*:
### `reduce` / `aggregate`
Apply a function to each item emitted by an Observable, sequentially, and emit the final value.
This function will perform a function on each element in the sequence until it is completed, then send a message with the aggregate value. It works much like the Swift `reduce` function works on sequences.
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/reduce.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/reduce.html )
*/
xample("aggregate") {
example("aggregate") {
let aggregateSubscriber = sequence(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
.aggregate(0, +)
.subscribeNext { value
.subscribeNext { value in
print("\(value)")
}
}
//: [Index](Index) - [Next >>](@next)

View File

@ -1,9 +1,7 @@
import Cocoa
//: [<< Previous](@previous) - [Index](Index)
import RxSwift
/*:
# To use playgrounds please open `Rx.xcworkspace`, build `RxSwift-OSX` scheme and then open playgrounds in `Rx.xcworkspace` tree view.
*/
/*:
## Observable Utility Operators
@ -19,18 +17,18 @@ Create an Disposable which listen events from source Observable, the given closu
example("subscribe") {
let intOb1 = PublishSubject<Int>()
intOb1
.subscribe { event in
print(event)
}
}
sendNext(intOb1, 1)
sendCompleted(intOb1)
}
e/*:
/*:
There are several variants of the `subscribe` operator. They works over one posible event type:
@ -39,104 +37,105 @@ There are several variants of the `subscribe` operator. They works over one posi
Create an Disposable which listen only Next event from source Observable, the given closure take the Even's value and is responsible for the actions to perform only when the Next even is produced.
*/
xample("subscribeNext") {
example("subscribeNext") {
let intOb1 = PublishSubject<Int>()
intOb1
.subscribeNext { int in
print(int)
}
}
sendNext(intOb1, 1)
sendCompleted(intOb1)
}
exa/*:
/*:
### `subscribeCompleted`
Create an Disposable which listen only Completed event from source Observable, the given closure take the Even's value and is responsible for the actions to perform only when the Completed even is produced.
*/
mple("subscribeCompleted") {
example("subscribeCompleted") {
let intOb1 = PublishSubject<Int>()
intOb1
.subscribeCompleted {
print("It's completed")
}
}
sendNext(intOb1, 1)
sendCompleted(intOb1)
}
examp/*:
/*:
### `subscribeError
Create an Disposable which listen only Error event from source Observable, the given closure take the Even's value and is responsible for the actions to perform only when the Error even is produced
Create an Disposable which listen only Error event from source Observable, the given closure take the Even's value and is responsible for the actions to perform only when the Error even is produced
*/
le("subscribeError") {
example("subscribeError") {
let intOb1 = PublishSubject<Int>()
intOb1
.subscribeError { error in
print(error)
}
}
sendNext(intOb1, 1)
sendError(intOb1, NSError(domain: "Examples", code: -1, userInfo: nil))
}
example/*:
### `do`
/*:
### `tap` a.k.a. `do`
Returns the same source Observable but the given closure responsible for the actions to perform when the even is produced. The gived closure obtain the event produced by the source observable
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/do.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/do.html )
*/
("do") {
example("tap") {
let intOb1 = PublishSubject<Int>()
let intOb2 = intOb1
.`do` { event in
.tap { event in
print("first \(event)")
}
}
intOb2
.subscribeNext { int in
print("second \(int)")
}
}
sendNext(intOb1, 1)
}
example("do/*:
/*:
### `tapOnNext` a.k.a. `doOnNext`
### `doOnNext`
It is a variant of the `do` operator. Returns the same source Observable but the given closure responsible for the actions to perform when the Next even is produced. The gived closure obtain the value of the Next event produced by the source observable.
It is a variant of the `tap` operator. Returns the same source Observable but the given closure responsible for the actions to perform when the Next even is produced. The gived closure obtain the value of the Next event produced by the source observable.
[More info in reactive.io website]( http://reactivex.io/documentation/operators/do.html )
*/
OnNext") {
example("tapOnNext") {
let intOb1 = PublishSubject<Int>()
let intOb2 = intOb1
.doOnNext { int in
.tapOnNext { int in
print("first \(int)")
}
}
intOb2
.subscribeNext { int in
print("second \(int)")
}
}
sendNext(intOb1, 1)
}
//: [Index](Index) - [Next >>](@next)

View File

@ -1,12 +1,7 @@
import Cocoa
//: [<< Previous](@previous) - [Index](Index)
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 {
@ -21,6 +16,10 @@ func writeSequenceToConsole(name: String, sequence: Observable<String>) {
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.
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/publishsubject.png)
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/publishsubject_error.png)
*/
example("PublishSubject") {
let subject = PublishSubject<String>()
@ -37,8 +36,8 @@ example("PublishSubject") {
## ReplaySubject
ReplaySubject emits to any observer all of the items, in the buffer, that were emitted by the source
ReplaySubject emits to any observer all of the items, in the buffer, that were emitted by the source
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/replaysubject.png)
*/
example("ReplaySubject") {
let subject = ReplaySubject<String>(bufferSize: 1)
@ -55,10 +54,13 @@ example("ReplaySubject") {
## BehaviorSubject a.k.a. Variable
ReplaySubject emits to any observer all of the items, in the buffer, that were emitted by the source
When an observer subscribes to a `BehaviorSubject`, it begins by emitting the item most recently emitted by the source Observable (or a seed/default value if none has yet been emitted) and then continues to emit any other items emitted later by the source Observable(s).
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/behaviorsubject.png)
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/behaviorsubject_error.png)
*/
example("ReplaySubject") {
example("BehaviorSubject") {
let subject = BehaviorSubject(value: "z")
writeSequenceToConsole("1", sequence: subject)
sendNext(subject, "a")
@ -67,3 +69,6 @@ example("ReplaySubject") {
sendNext(subject, "c")
sendNext(subject, "d")
}
//: [Index](Index) - [Next >>](@next)

View File

@ -1,9 +1,6 @@
import Cocoa
import RxSwift
//: [<< Previous](@previous) - [Index](Index)
/*:
# To use playgrounds please open `Rx.xcworkspace`, build `RxSwift-OSX` scheme and then open playgrounds in `Rx.xcworkspace` tree view.
*/
import RxSwift
/*:
## Transforming Observables
@ -14,45 +11,49 @@ Operators that transform items that are emitted by an Observable.
### `map` / `select`
Transform the items emitted by an Observable by applying a function to each item
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/map.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/map.html )
*/
example("map") {
let observable1: Observable<Character> = create { observer in
sendNext(observer, Character("A"))
sendNext(observer, Character("B"))
sendNext(observer, Character("C"))
return AnonymousDisposable {}
}
observable1
.map { char in
char.hashValue
}
.subscribeNext { int in
print(int)
}
}
}
e/*:
/*:
### `flatMap`
Transform the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/flatmap.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/flatmap.html )
*/
xample("flatMap") {
example("flatMap") {
let observable1: Observable<Int> = create { observer in
sendNext(observer, 1)
sendNext(observer, 2)
sendNext(observer, 3)
return AnonymousDisposable {}
}
let observable2: Observable<String> = create { observer in
sendNext(observer, "A")
sendNext(observer, "B")
@ -60,10 +61,10 @@ xample("flatMap") {
sendNext(observer, "D")
sendNext(observer, "F")
sendNext(observer, "--")
return AnonymousDisposable {}
}
observable1
.flatMap { int in
observable2
@ -74,14 +75,16 @@ xample("flatMap") {
}
exa/*:
/*:
### `scan`
Apply a function to each item emitted by an Observable, sequentially, and emit each successive value
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/scan.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/scan.html )
*/
mple("scan") {
example("scan") {
let observable: Observable<Int> = create { observer in
sendNext(observer, 0)
sendNext(observer, 1)
@ -89,10 +92,10 @@ mple("scan") {
sendNext(observer, 3)
sendNext(observer, 4)
sendNext(observer, 5)
return AnonymousDisposable {}
}
observable
.scan(0) { acum, elem in
acum + elem
@ -101,3 +104,6 @@ mple("scan") {
print($0)
}
}
//: [Index](Index) - [Next >>](@next)

View File

@ -1,12 +1,11 @@
import Foundation
public func example(description: String, action: () -> ()) {
print("\n--- \(description) example ---")
action()
}
import Foundation
public func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='6.0' target-platform='osx' requires-full-environment='true' display-mode='rendered'>
<pages>
<page name='Index'/>
<page name='Introduction'/>
<page name='Subjects'/>
<page name='Creating_observables'/>
<page name='Transforming_Observables'/>
<page name='Filtering_Observables'/>
<page name='Combining_Observables'/>
<page name='Error_Handling_Operators'/>
<page name='Observable_Utility_Operators'/>
<page name='Conditional_and_Boolean_Operators'/>
<page name='Mathematical_and_Aggregate_Operators'/>
<page name='Connectable_Observable_Operators'/>
</pages>
</playground>