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

- 程序員修煉之道:從小工到專家
- 云計算環境下的信息資源集成與服務
- Visual Studio 2015 Cookbook(Second Edition)
- Spark核心技術與高級應用
- Hadoop大數據實戰權威指南(第2版)
- Python金融實戰
- AI時代的數據價值創造:從數據底座到大模型應用落地
- 大數據分析:數據倉庫項目實戰
- Visual Studio 2013 and .NET 4.5 Expert Cookbook
- 大數據與機器學習:實踐方法與行業案例
- MySQL數據庫應用與管理
- 數據庫原理及應用:SQL Server 2016
- MySQL核心技術手冊
- 數字孿生
- GameMaker Game Programming with GML