- Reactive Programming in Kotlin
- Rivu Chakraborty
- 246字
- 2021-07-02 22:26:41
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).
- MySQL高可用解決方案:從主從復(fù)制到InnoDB Cluster架構(gòu)
- 數(shù)據(jù)庫(kù)應(yīng)用實(shí)戰(zhàn)
- Unity 5.x Game AI Programming Cookbook
- Spark快速大數(shù)據(jù)分析(第2版)
- Mastering Ninject for Dependency Injection
- 計(jì)算機(jī)信息技術(shù)基礎(chǔ)實(shí)驗(yàn)與習(xí)題
- Effective Amazon Machine Learning
- 大數(shù)據(jù)算法
- 數(shù)據(jù)庫(kù)應(yīng)用基礎(chǔ)教程(Visual FoxPro 9.0)
- 數(shù)據(jù)驅(qū)動(dòng):從方法到實(shí)踐
- 深入淺出 Hyperscan:高性能正則表達(dá)式算法原理與設(shè)計(jì)
- 數(shù)據(jù)庫(kù)設(shè)計(jì)與應(yīng)用(SQL Server 2014)(第二版)
- Oracle PL/SQL實(shí)例精解(原書第5版)
- 二進(jìn)制分析實(shí)戰(zhàn)
- Visual Studio 2013 and .NET 4.5 Expert Cookbook