我有2种方法:
private void method1() throws InterruptedException {
//SimulateLongOperation
Thread.sleep(5000);
System.out.println("hello1");
}
private void method2(){
System.out.println("hello2");
}
我想在method1完成时调用method2,但我不想阻止UI线程。 可以用RxJava做到吗? 它会是什么样子的?互联网上没有简单的例子,只有很多我无法理解的文章。
当我调用时:
method1();
method2();
我阻止主线程,这太可怕了。
您还可以尝试以下方法:
Completable.fromAction{ method1() }
.doOnComplete{ method2() }
.subscribeOn(Schedulers.io())
.subscribe()
Completable.fromAction(() -> method1() )
.doOnComplete(__ -> method2())
.subscribeOn(Schedulers.io())
.subscribe()
由于您正在寻找一个非常具体的答案,我将在这里发布一个天真的实现。根据您的用例,可能有更好的解决方案。
private void method1() throws InterruptedException {
//SimulateLongOperation
Thread.sleep(5000);
System.out.println("hello1");
}
private void method2(){
System.out.println("hello2");
}
void solution() {
Observable<Void> first = Observable.fromCallable(() -> {
method1();
return null;
});
Observable<Void> second = Observable.fromCallable(() -> {
method2();
return null;
});
first.flatMap((Function<Void, ObservableSource<?>>) aVoid -> second)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe();
}