上QQ阅读APP看书,第一时间看更新
Understanding the toObservable extension function
Thanks to the extension functions of Kotlin, you can turn any Iterable instance, such as List, to Observable without much effort; we have already used this method in Chapter 1, A Short Introduction to Reactive Programming, however, take a look at this:
fun main(args: Array<String>) { val observer: Observer<String> = object : Observer<String> { override fun onComplete() { println("All Completed") } override fun onNext(item: String) { println("Next $item") } override fun onError(e: Throwable) { println("Error Occured ${e.message}") } override fun onSubscribe(d: Disposable) { println("New Subscription ") } }//Create Observer val list:List<String> = listOf
("String 1","String 2","String 3","String 4") val observable:Observable<String> = list.toObservable() observable.subscribe(observer) }
And the following is the output:
So, aren't you curious to look into the toObservable method? Let's do it. You can find this method inside the observable.kt file provided with the RxKotlin package:
fun <T : Any> Iterator<T>.toObservable(): Observable<T> =
toIterable().toObservable() fun <T : Any> Iterable<T>.toObservable(): Observable<T> =
Observable.fromIterable(this) fun <T : Any> Sequence<T>.toObservable(): Observable<T> =
asIterable().toObservable() fun <T : Any> Iterable<Observable<out T>>.merge(): Observable<T> =
Observable.merge(this.toObservable()) fun <T : Any> Iterable<Observable<out T>>.mergeDelayError():
Observable<T> = Observable.mergeDelayError(this.toObservable())
So, it basically uses the Observable.from method internally; thanks again to extension functions of Kotlin.