I have a list of tasks which should be handled one-by-one in a new thread and then the result should be displayed in a method by some main thread.
However this doesn't seem to work, the flatMap
method is invoked in the main thread.
Why does not the subscribeOn
method handle the "thread switch" in this case?
What would be a better pattern to execute some work in another thread? (except from using Observable.create
and creating a new thread manually, which is very verbose)
List<Task> tasks = ...;
Observable.from(tasks)
.flatMap(task -> {
// should be handled in a new thread
try {
return Observable.just(task.call());
} catch (Exception e) {
log.error("Error", e);
}
return Observable.empty();
})
.subscribeOn(Schedulers.newThread())
.observeOn(MySchedulers.main())
.subscribe(this::show); // subscribe called from main thread