在RxJava中,"block()"、"subscribe()"和"subscribe(-)"都是用于触发Observable流的方法,但它们之间有一些区别。
下面是使用block()方法的示例代码:
Observable.just("Hello World")
.delay(1, TimeUnit.SECONDS)
.blockingSubscribe(new Consumer() {
@Override
public void accept(String s) throws Exception {
System.out.println(s);
}
});
下面是使用subscribe()方法的示例代码:
Observable.just("Hello World")
.delay(1, TimeUnit.SECONDS)
.subscribe(new Consumer() {
@Override
public void accept(String s) throws Exception {
System.out.println(s);
}
});
下面是使用subscribe(-)方法的示例代码:
Observable.just("Hello World")
.delay(1, TimeUnit.SECONDS)
.subscribe(
new Consumer() {
@Override
public void accept(String s) throws Exception {
System.out.println(s);
}
},
new Consumer() {
@Override
public void accept(Throwable throwable) throws Exception {
throwable.printStackTrace();
}
},
new Action() {
@Override
public void run() throws Exception {
System.out.println("Completed");
}
}
);
总结: