0

I'm relatively new to RxJava and I'm curious about how to use Futures with RxJava's Observable and/or Single. What I'm trying to make is a system to connect to a MongoDB database and load MongoDB collections. I would imagine that I could use Observable.fromFuture(new FutureTask<>()) and the FutureTask's Callable would handle the database connection then return true if it connected.

Now just for learning how to use Futures and Observables (or Singles), I created something very simple like so:

Debugger.warning("Begin Future");
FutureObserver<String> observer = Observable.<String>fromFuture(new FutureTask<>(new 
        Callable<String>() {
            @Override
            public String call() throws Exception {
                return "Hello World";
            }
        }))
.doFinally(() -> Debugger.warning("Do Finally"))
.subscribeWith(new FutureObserver<>());

try {
   Debugger.warning("Observer: " + observer.get());
} catch (Exception e) {
   e.printStackTrace();
}

My Debugger simply prints to console. "Begin Future" is printed and the thread is then blocked and nothing happens, indefinitely. I know that when I actually use this within my codebase, I should have .subscribeOn(Schedulers.io()), but for testing's sake, I left that out. I've spent the past couple days searching YouTube and Google searches for examples of how to use Futures with RxJava 3, and I just can't seem to figure this out. I appreciate any help or direction!

Atlas
  • 9
  • 3
  • Why do you use `FutureTask`? You could just simply use `fromCallable` with your MongoDB access code (plus `subscribeOn(io())`). We have [Wiki](https://github.com/ReactiveX/RxJava/wiki/Creating-Observables#fromfuture) examples. – akarnokd Jan 20 '22 at 20:01
  • Oh okay, thank you! In my mind, the way it would work is that I would use the `FutureTask` to notify the particular service or class trying to fetch information from the database when the connection had been established and was ready to be used. Perhaps that's the wrong way to use it. – Atlas Jan 20 '22 at 20:32

0 Answers0