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

Understanding the Observable.just method

Another interesting factory method is Observable.just; this method creates Observable and adds the parameters passed to it as the only items of the Observable. Note that if you pass an Iterable instance to Observable.just as a single parameter, it will take the entire list as a single item, unlike Observable.from, where it will create items of Observable from each item in Iterable.

Here is what happens when you call Observable.just:

  • You call Observable.just with parameters
  • Observable.just will create Observable
  • It will emit each of its parameters as the onNext notification
  • When all parameters are emitted successfully, it will emit the onComplete notification

Let's look at this code example to understand it better:

    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.just("A String").subscribe(observer) 
       Observable.just(54).subscribe(observer) 
       Observable.just(listOf("String 1","String 2","String 3",
"String 4")).subscribe(observer) Observable.just(mapOf(Pair("Key 1","Value 1"),Pair
("Key 2","Value 2"),Pair("Key 3","Value
3"))).subscribe(observer) Observable.just(arrayListOf(1,2,3,4,5,6)).subscribe(observer) Observable.just("String 1","String 2",
"String 3").subscribe(observer)//1 }

And here is the output:

As you can see in the output, lists and maps are also treated as a single item, but look at comment 1 in the code where I passed three strings as parameters of the Observable.just method. Observable.just took each of the parameters as a separate item and emitted them accordingly (see the output).

主站蜘蛛池模板: 鄂托克前旗| 平罗县| 准格尔旗| 土默特右旗| 阿荣旗| 肃南| 奉节县| 阳信县| 杭锦旗| 榕江县| 遂川县| 临西县| 南昌市| 汉沽区| 田东县| 江阴市| 乌鲁木齐县| 清涧县| 锡林浩特市| 蛟河市| 潮安县| 清镇市| 长治县| 棋牌| 钦州市| 凤台县| 隆回县| 玉田县| 昌平区| 密山市| 隆安县| 博爱县| 南岸区| 龙门县| 新晃| 云霄县| 清流县| 宁远县| 炉霍县| 五大连池市| 儋州市|