- 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:

- Microsoft SQL Server企業級平臺管理實踐
- DB29forLinux,UNIX,Windows數據庫管理認證指南
- 虛擬化與云計算
- 智能數據時代:企業大數據戰略與實戰
- 數據庫設計與應用(SQL Server 2014)(第二版)
- 數據科學工程實踐:用戶行為分析與建模、A/B實驗、SQLFlow
- INSTANT Android Fragmentation Management How-to
- 數據庫應用系統開發實例
- 數字IC設計入門(微課視頻版)
- 實用數據結構
- 數據庫查詢優化器的藝術:原理解析與SQL性能優化
- 大數據技術體系詳解:原理、架構與實踐
- Trino權威指南(原書第2版)
- 精通Neo4j
- 數據產品經理寶典:大數據時代如何創造卓越產品