【Android】Analysis of Empty Observable in RxJava

About Empty Observable

In rxjava, there is a function called Observable.empty()

This function return an object that is instance of ObservableEmpty

This class will emit a complete event instead of next event, then rx chain will ended

Empty Observable with Map Operator

Now let's test what will happen, when ObservableEmpty is not top level observables

I means it was mapped from other observables by operator such as flatMap

Trial Code
kotlin 复制代码
Observable.just(1, 2, 3, 4, 5, 6, 7, 8, 9)
    .flatMap {
        if (it != 5) {
            return@flatMap Observable.just(it.toString())
        }
        return@flatMap Observable.empty<String>()
    }
    .doOnNext { println(it) }
    .subscribe()

We get this result

shell 复制代码
1
2
3
4
6
7
8
9

When it's a mediator observable, it won't interrupt all top observables

It just break the sub event stream that related to itself

Empty Observable with ConcatArray Operator

This time, we make it the top ones, but not the single one

We combine it with other normal observables by concatArray , as top level observable in total

kotlin 复制代码
Observable.concatArray(
    Observable.just(1),
    Observable.just(2),
    Observable.just(3),
    Observable.empty(),
    Observable.just(4),
    Observable.just(5)
).flatMap {
    if (it != 5) {
        return@flatMap Observable.just(it.toString())
    }
    return@flatMap Observable.empty<String>()
}
    .doOnNext { println(it) }
    .subscribe()

This is the output

shell 复制代码
1
2
3
4

We can see that, ObservableEmpty interrupt other observables in the same level

Also, it interrupt the whole rx chain, directlly jump to onComplete

Summary
  • ObservableEmpty will interrupt datas or observables mapped from it

  • ObservableEmpty will interrupt observables at same level, but after it in order

Bless

Lesson is Over, Have A Rest, and Enjoy Your Life .

Good Work, Good Study, Good Progress, and Good Mood !

相关推荐
repinkply29 分钟前
Android Camera性能优化概述
android·linux·性能优化·camera
alexhilton3 小时前
让Activity更加优雅地跳转
android·kotlin·android jetpack
zzlyx993 小时前
HarmonyOS与Android在设计理念、系统架构、性能优化等方面全面对比
android·系统架构·harmonyos
dd06s3 小时前
安卓使用.9图实现阴影效果box-shadow: 0 2px 6px 1px rgba(0,0,0,0.08);
android
榴月子4 小时前
SQLite在安卓中的应用
android·sqlite
顾北川_野4 小时前
Android 默认开启深色主题模式(暗夜模式)
android·java
彭于晏6895 小时前
Jetpack-ViewModel+LiveData+DataBinding
android·java·android-studio
kingsley12126 小时前
记录一下,android studio 登录不上github的问题
android·github·android studio
花追雨9 小时前
Android -- [SelfView] 自定义多色渐变背景板
android·gitee