Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava: CountDownLatch never stop

Recently, I'm learning RxJava. We all know CountDownLatch will stop when counting to zero. Well, but when I run code below, CountDownLaych never stop! And I try to run same code as Java project, it's ok to stop!

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final CountDownLatch latch = new CountDownLatch(5);
    Observable
            .interval(1, TimeUnit.SECONDS)
            .subscribe(new Action1<Long>() {
                @Override
                public void call(Long counter) {
                    latch.countDown();
                    long count = latch.getCount();
                    Log.d(TAG, "call get -> " + counter + ", latch count -> " + count);
                }
            });

    try {
        latch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

In Android Studio, These code will output like:

D/MainActivity: call get -> 0, latch count -> 4
D/MainActivity: call get -> 1, latch count -> 3
D/MainActivity: call get -> 2, latch count -> 2
D/MainActivity: call get -> 3, latch count -> 1
D/MainActivity: call get -> 4, latch count -> 0
D/MainActivity: call get -> 5, latch count -> 0
D/MainActivity: call get -> 6, latch count -> 0
D/MainActivity: call get -> 7, latch count -> 0
....
like image 712
HuangDong.Li Avatar asked May 12 '26 23:05

HuangDong.Li


1 Answers

According to the documentation a latch doesn't stop counting at zero. Instead:

If the current count equals zero then nothing happens.

Try modifying your try block to look like this:

Log.d(TAG, "call await");
latch.await();
Log.d(TAG, "released");

I am sure then you'll see that the thread is released when your latch reaches zero. If you want your observable to stop emitting when that happens then you'll have to unsubscribe from it.

like image 189
Marcin Koziński Avatar answered May 16 '26 07:05

Marcin Koziński