The Observable.from methods

The Observable.from methods are comparatively simpler than the Observable.create method. You can create the Observable instances from nearly every Kotlin structure with the help of from methods.

In RxKotlin 1, you will have Observale.from as a method; however, from RxKotlin 2.0 (as with RxJava2.0), operator overloads have been renamed with a postfix, such as fromArray, fromIterable, and fromFuture.

Let's take a look at the following code:

fun main(args: Array<String>) { 
 
    val observer: Observer<String> = object : Observer<String> { 
        override fun onComplete() { 
            println("Completed") 
        } 
 
        override fun onNext(item: String) { 
            println("Received-> $item") 
        } 
 
        override fun onError(e: Throwable) { 
            println("Error Occured => ${e.message}") 
        } 
 
        override fun onSubscribe(d: Disposable) { 
            println("Subscription") 
        } 
    }//Create Observer 
 
    val list = listOf("Str 1","Str 2","Str 3","Str 4") 
    val observableFromIterable: Observable<String> = Observable.fromIterable(list)//1 
    observableFromIterable.subscribe(observer) 
 
 
    val callable = object : Callable<String> { 
        override fun call(): String { 
            return "I'm From Callable" 
        } 
 
    } 
    val observableFromCallable:Observable<String> = Observable.fromCallable(callable)//2 
    observableFromCallable.subscribe(observer) 
 
    val future:Future<String> = object : Future<String> { 
        val retStr = "I'm from Future" 
 
        override fun get() = retStr 
 
        override fun get(timeout: Long, unit: TimeUnit?)  = retStr 
 
        override fun isDone(): Boolean = true 
 
        override fun isCancelled(): Boolean = false 
 
        override fun cancel(mayInterruptIfRunning: Boolean): Boolean = false 
 
    } 
    val observableFromFuture:Observable<String> = Observable.fromFuture(future)//3 
    observableFromFuture.subscribe(observer) 
} 

At comment 1, we used the Observable.fromIterable method to create Observable from an Iterable instance (here, list). At comment 2. We called the Observable.fromCallable method to create Observable from a Callable instance, we did the same at comment 3, where we called the Observable.fromFuture method to derive Observable from a Future instance.

Here is the output:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.32.222