我们如何在当前/初始线程上观察到结果?在android上我们可以使用observerOn(AndroidSchedulers.mainThread())
,但是如果是简单的应用程序,如何做到这一点,例如。用于服务器端应用程序。
public void testParallelZip() throws InterruptedException {
Maybe.zip(
getStrings("first", 2000, "One", "Two").subscribeOn(Schedulers.computation()),
getStrings("second", 1000, "Three", "Four").subscribeOn(Schedulers.computation()),
getStrings("third", 1000, "Five", "Six").subscribeOn(Schedulers.computation()),
mergeStringLists())
// .observeOn(AndroidSchedulers.mainThread()) Where to observe
.subscribe(strings -> {
System.out.println("result on " + Thread.currentThread().getName());
System.out.println(strings);
},
throwable -> System.out.println("oops"),
() -> System.out.println("Completed "));
System.out.println("exit");
}
private static Maybe<List<String>> getStrings(String tag, int delay, final String str1, final String str2) {
return Maybe.fromCallable(() -> {
sleep(tag, delay);
List<String> strings = new ArrayList<>();
strings.add(str1);
strings.add(str2);
return strings;
});
}
private static void sleep(String tag, int time) {
try {
System.out.println(">Tag " + tag + " running on " + Thread.currentThread().getName());
Thread.sleep(time);
System.out.println("Tag " + tag + " running on " + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static Function3<List<String>, List<String>, List<String>, List<String>> mergeStringLists() {
return (strings, strings2, strings3) -> {
System.out.println("merging in " + Thread.currentThread().getName());
for (String s : strings2) {
strings.add(s);
}
for (String s : strings3) {
strings.add(s);
}
return strings;
};
}
我尝试了this,即使用Schedulers.from(),但需要手动调用tasks.take().run()
。可能有更好的方法吗?
tasks = LinkedBlockingQueue<Runnable>()
Maybe.zip(
getStrings("first", 2000, "One", "Two").subscribeOn(Schedulers.computation()),
getStrings("second", 1000, "Three", "Four").subscribeOn(Schedulers.computation()),
getStrings("third", 1000, "Five", "Six").subscribeOn(Schedulers.computation()),
mergeStringLists())
.observeOn(Schedulers.from(Executor { runnable ->
tasks.add(runnable) }))
.subscribe(strings -> {
System.out.println("result on " + Thread.currentThread().getName());
System.out.println(strings);
},
throwable -> System.out.println("oops"),
() -> System.out.println("Completed "));
tasks.take().run()