Swift Language Creating observables


Example

RxSwift offers many ways to create an Observable, let's take a look:

import RxSwift

let intObservale = Observable.just(123) // Observable<Int>
let stringObservale = Observable.just("RxSwift") // Observable<String>
let doubleObservale = Observable.just(3.14) // Observable<Double>

So, the observables are created. They holds just one value and then terminates with success. Nevertheless, nothing happening after it was created. Why?

There are two steps in working with Observables: you observe something to create a stream and then you subscribe to the stream or bind it to something to interact with it.

Observable.just(12).subscribe {
    print($0)
}

The console will print:

.Next(12)
.Completed()

And if I interested only in working with data, which take place in .Next events, I'd use subscribeNext operator:

Observable.just(12).subscribeNext {
    print($0) // prints "12" now
}

If I want create an observable of many values, I use different operators:

Observable.of(1,2,3,4,5).subscribeNext {
    print($0)
}
// 1
// 2
// 3
// 4
// 5

// I can represent existing data types as Observables also:
[1,2,3,4,5].asObservable().subscribeNext { 
    print($0) 
}
// result is the same as before.

And finally, maybe I want an Observable that does some work. For example, it is convenient to wrap a network operation into Observable<SomeResultType>. Let's take a look of do one can achieve this:

Observable.create { observer in    // create an Observable ...
    MyNetworkService.doSomeWorkWithCompletion { (result, error) in
        if let e = error {
            observer.onError(e)    // ..that either holds an error
        } else {
            observer.onNext(result) // ..or emits the data
            observer.onCompleted()  // ..and terminates successfully.
        }
    }
    return NopDisposable.instance // here you can manually free any resources
                                //in case if this observable is being disposed.
}