官术网_书友最值得收藏!

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:

主站蜘蛛池模板: 陆河县| 育儿| 利辛县| 博兴县| 齐齐哈尔市| 通辽市| 西和县| 绵竹市| 吉安市| 阳曲县| 蒙山县| 荥阳市| 民乐县| 古蔺县| 平遥县| 三台县| 剑川县| 德化县| 定西市| 通许县| 南雄市| 山东| 徐州市| 柳州市| 祁连县| 五常市| 刚察县| 江源县| 蕲春县| 独山县| 桑日县| 资兴市| 濮阳县| 随州市| 桐庐县| 合肥市| 临海市| 洪湖市| 古蔺县| 文昌市| 崇仁县|