Understanding the Observable.from methods

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

Note that 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, fromFuture, and so on.

So, let's take a look at this code:

    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 = listOf("String 1","String 2","String 3","String 4") 
      val observableFromIterable: Observable<String> =
Observable.fromIterable(list)//1 observableFromIterable.subscribe(observer) val callable = object : Callable<String> { override fun call(): String { return "From Callable" } } val observableFromCallable:Observable<String> =
Observable.fromCallable(callable)//2 observableFromCallable.subscribe(observer) val future:Future<String> = object :Future<String> { override fun get(): String = "Hello From Future" override fun get(timeout: Long, unit: TimeUnit?): String =
"Hello From Future" 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) }

On comment 1, I used the Observable.fromIterable method to create Observable from an Iterable instance (here, List). On comment 2, I called the Observable.fromCallable method to create Observable from a Callable instance, and same for comment 3, where I 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.117.11.247