3

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
....
HuangDong.Li
  • 291
  • 1
  • 2
  • 9

1 Answers1

4

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.

Dave Moten
  • 11,957
  • 2
  • 40
  • 47
Marcin Koziński
  • 10,835
  • 3
  • 47
  • 61