- Reactive Programming in Kotlin
- Rivu Chakraborty
- 261字
- 2021-07-02 22:26:41
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:

- 數據庫技術與應用教程(Access)
- 正則表達式必知必會
- 企業大數據系統構建實戰:技術、架構、實施與應用
- 新型數據庫系統:原理、架構與實踐
- 圖解機器學習算法
- 文本挖掘:基于R語言的整潔工具
- 達夢數據庫性能優化
- Dependency Injection with AngularJS
- Spark大數據分析實戰
- Hands-On Mathematics for Deep Learning
- MATLAB Graphics and Data Visualization Cookbook
- Apache Kylin權威指南
- Unreal Engine Virtual Reality Quick Start Guide
- 菜鳥學SPSS數據分析
- 數據庫與數據處理:Access 2010實現