RxJava2 merged Observable doesn't stop

时间:2018-06-19 11:16:00

标签: android rx-java reactive-programming rx-java2

Why merge operator doesn't stopped after obs2 onCompleted? I am looking at diagram from this book

"Reactive Programming on Android with RxJava"

enter image description here

From my point of view if any of merged Observables is onCompleted, then another Observable also terminates (completed).

But its not. why so?

Here is my code. Obs1 should terminate just after Obs2, but it is endless

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = findViewById(R.id.btn);

        Observable.merge(obs1, obs2)
                .subscribe(data -> Log.d(TAG, String.valueOf(data)));
    }

    Observable<String> obs1 = Observable.interval(1, TimeUnit.SECONDS)
            .map(data -> "obs1: " + data);

    Observable obs2 =
            Observable.just(1, 2, 3, 4, 5)
                    .delay(1, TimeUnit.SECONDS)
                    .filter(data -> data < 5)
                    .map(data -> "obs2: " + data)
                    .doOnComplete(() -> Log.d(TAG, "done"));

D/MainActivity: obs1: 0
                obs2: 1
                obs2: 2
                obs2: 3
D/MainActivity: obs2: 4
                done
D/MainActivity: obs1: 1
D/MainActivity: obs1: 2
D/MainActivity: obs1: 3
D/MainActivity: obs1: 4
D/MainActivity: obs1: 5
D/MainActivity: obs1: 6

1 个答案:

答案 0 :(得分:1)

这是正常行为,因为第一个可观察到的物体仍每秒发射一次。合并运算符的onComplete方法只有在观察到名为onpmplete方法的项目

时才触发