如何使用 RxJava 间隔运算符 [英] How to use RxJava Interval Operator

查看:40
本文介绍了如何使用 RxJava 间隔运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 RxJava 运算符,但我发现下面的这些代码没有打印任何内容:

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

public static void main(String[] args) {

    Observable
    .interval(1, TimeUnit.SECONDS)
    .subscribe(new Subscriber<Long>() {
        @Override
        public void onCompleted() {
            System.out.println("onCompleted");
        }

        @Override
        public void onError(Throwable e) {
            System.out.println("onError -> " + e.getMessage());
        }

        @Override
        public void onNext(Long l) {
            System.out.println("onNext -> " + l);
        }
    });
}

作为 ReactiveX,interval

As ReactiveX, interval

创建一个 Observable,它发出以特定时间间隔间隔的整数序列

create an Observable that emits a sequence of integers spaced by a particular time interval

我是否犯了错误或忘记了什么?

Did I make a mistake or forget about something?

推荐答案

你必须阻塞直到 observable 被消耗:

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<Long>() {
        @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();
}

你可以添加 .take(10) 来查看完整的 observable.

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

这篇关于如何使用 RxJava 间隔运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆