如何异步运行This Observable?

时间:2015-04-19 10:28:35

标签: reactive-programming rx-java

我有以下服务模仿一些阻塞IO操作:

public class StudentService{

public List<Student> getStudentAslist(){

            Thread.sleep(10000);
.....
        return students;
    }
}

现在我正在尝试使用Java 8环境在FutureTask<T>内运行此服务:

     StudentService studentService = new StudentService();  
     FutureTask<List<Student>> future = new FutureTask<>(()-> studentService.getStudentAslist());

     Worker worker = Schedulers.io().createWorker();
            worker.schedule(()->future.run());


     Observable<Student> observable2 = Observable.from(future).flatMap(Observable::from);
    observable2.filter((s)-> s.getAge()>40).subscribe(student->System.out.println(student));

    System.out.println("end");

然而,最终的印刷“结束”仅在10秒后打印出来,所以看起来我完全同步,

我如何反应性地运行它?

2 个答案:

答案 0 :(得分:2)

我认为你要找的是.subscribeOn

FutureTask<List<String>> future = new FutureTask<>(this::getStudentAslist);

Scheduler.Worker worker = Schedulers.io().createWorker();
worker.schedule(future::run);

Observable.from(future)
        .subscribeOn(Schedulers.computation())
        .flatMapIterable(s -> s)
        .subscribe(System.out::println);
System.out.println("marker");


TimeUnit.SECONDS.sleep(3);

供参考:

public List<String> getStudentAslist(){
    try {
        TimeUnit.SECONDS.sleep(3);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    return Collections.singletonList("finished");
}

答案 1 :(得分:2)

您可以使用延迟将所有工作转移到Observable

FutureTask<List<String>> future = new FutureTask<>(this::getStudentAslist);

Observable<List<Student>> studentsObservable = Observable
        .defer(() -> {
            future.run();
            return Observable.from(future);
        });

然后使用 subscribeOn 来决定将哪个线程用于此Observable

studentsObservable
        .flatMapIterable(students -> students)
        .filter((s) -> s.getAge() > 40)
        .subscribeOn(Schedulers.computation())
        .subscribe(student -> System.out.println(student));