How to use RxJava Interval Operator

后端 未结 3 875
我在风中等你
我在风中等你 2021-01-17 11:33

I\'m learning about RxJava operator, and I found these code below did not print anything:

public static void main(String[] args) {

    Observable
    .inter         


        
3条回答
  •  伪装坚强ぢ
    2021-01-17 11:48

    You have to block until the observable is consumed:

    public static void main(String[] args) throws Exception {
    
        CountDownLatch latch = new CountDownLatch(1);
    
        Observable
        .interval(1, TimeUnit.SECONDS)
        .subscribe(new Subscriber() {
            @Override
            public void onCompleted() {
                System.out.println("onCompleted");
                // make sure to complete only when observable is done
                latch.countDown();
            }
    
            @Override
            public void onError(Throwable e) {
                System.out.println("onError -> " + e.getMessage());
            }
    
            @Override
            public void onNext(Long l) {
                System.out.println("onNext -> " + l);
            }
        });
    
        // wait for observable to complete (never in this case...)
        latch.await();
    }
    

    You can add .take(10) for example to see the observable complete.

提交回复
热议问题