- Reactive Programming in Kotlin
- Rivu Chakraborty
- 231字
- 2021-07-02 22:26:42
Other Observable factory methods
Before moving forward with Observer, subscribing, unsubscribing, and Subjects, let's try our hands on a few other factory methods of Observable.
So, let's look at this code first, and then we will try to learn it line by line:
fun main(args: Array<String>) { val observer: Observer<Any> = object : Observer<Any> { override fun onComplete() { println("All Completed") } override fun onNext(item: Any) { println("Next $item") } override fun onError(e: Throwable) { println("Error Occured ${e.message}") } override fun onSubscribe(d: Disposable) { println("New Subscription ") } }//Create Observer Observable.range(1,10).subscribe(observer)//(1) Observable.empty<String>().subscribe(observer)//(2) runBlocking {
Observable.interval(300,TimeUnit.MILLISECONDS).
subscribe(observer)//(3) delay(900) Observable.timer(400,TimeUnit.MILLISECONDS).
subscribe(observer)//(4) delay(450) } }
On comment (1), we created Observable with the Observable.range() factory method. This method creates an Observable and emits integers with the supplied start parameter until it emits a number of integers as per the count parameter.
On comment (2), we created Observable with the Observable.empty() method. This method creates Observable and emits onComplete() right away, without emitting any items with onNext().
On comment (3) and comment (4), we used two interesting Observable factory methods. The method on comment (3), Observable.interval(), emits numbers sequentially starting from 0, after each specified interval. It will continue emitting until you unsubscribe and until the program runs. Whereas, the method on comment (4), Observable.timer(), will emit only once with 0 after the specified time elapsed.
Here is the output if you are curious:

- 大規模數據分析和建模:基于Spark與R
- Hands-On Machine Learning with Microsoft Excel 2019
- Test-Driven Development with Mockito
- 計算機信息技術基礎實驗與習題
- 跟老男孩學Linux運維:MySQL入門與提高實踐
- “互聯網+”時代立體化計算機組
- 數據庫原理與設計(第2版)
- MATLAB Graphics and Data Visualization Cookbook
- 云數據中心網絡與SDN:技術架構與實現
- Hadoop大數據開發案例教程與項目實戰(在線實驗+在線自測)
- 視覺大數據智能分析算法實戰
- Power BI智能數據分析與可視化從入門到精通
- Hadoop 3實戰指南
- 大數據測試技術:數據采集、分析與測試實踐(在線實驗+在線自測)
- 代碼的未來