the Future class represents a future result of an asynchronous computation – a result that will eventually appear in the Future after the processing is complete.
public class SquareCalculator { private ExecutorService executor = Executors.newSingleThreadExecutor(); public Future<Integer> calculate(Integer input) { return executor.submit(() -> { Thread.sleep(1000); return input * input; }); } }
Given a pre-existing, already running or already completed java.util.concurrent.Future
, wait for the Future
to complete normally or with an exception in a blocking fashion and relay the produced value or exception to the consumers.
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); Future<String> future = executor.schedule(() -> "Hello world!", 1, TimeUnit.SECONDS); Observable<String> observable = Observable.fromFuture(future); observable.subscribe( item -> System.out.println(item), error -> error.printStackTrace(), () -> System.out.println("Done")); executor.shutdown();
References
https://github.com/ReactiveX/RxJava/wiki/Creating-Observables#fromfuture
https://www.baeldung.com/java-future