gpt4 book ai didi

rx-java - 如何使用 RxJava 间隔运算符

转载 作者:行者123 更新时间:2023-12-02 05:42:51 26 4
gpt4 key购买 nike

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

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,间隔

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

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

最佳答案

您必须阻塞直到可观察对象被消耗:

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) 以查看可观察的完整内容。

关于rx-java - 如何使用 RxJava 间隔运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37652952/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com