TIL 5: Made your retrofit rest client reactive a little bit.

Aliaksandr Rasolka
2 min readJul 6, 2018

--

Just apply right adapter.

Photo by Hello I’m Nik on Unsplash

Day-to-day I’m using Retrofit2 client and all going flawless until I start using call asynchronously and try to chain operations.

First chapter.

So, what I have on start?

API client:

And service that implement this interface:

And use it:

Nothing special but it works. And works well.

Unfortunately new logic required some changes.

Second chapter.

What if you need to login and execute 2 tasks in parallel using access token from login method? This case I decide to use CompletableFuture from Java 8.

On this level I modify only test logic:

So, easy using, not much code changes… but with this implementation I should wrap each standalone future with CompletableFuture and pass lambda with function that execute API call.

Weird. Let’s find some cool solution.

Third chapter.

Search a little… and more… boo — official implementation with documentation :D

Let’s tune this code out. Since I use Gradle — apply required script and fetch library:

implementation("com.squareup.retrofit2:adapter-java8:2.4.0")

Register adapter to your Retrofit:

Tune API client to return ready CompletableFutures:

Modify your service with future workaround. This place you can even handle result and remove try/catch construction:

Finally let’s change out test:

As you can see for direct API call no need to pass functions — awesome.

Now you just need to worry about chain calls :D

Finally cut out results:

  1. All API calls async by default.
  2. Call will be executed only when you access future data any way. For example future.get() or future.join() methods calls.
  3. No need to think about wrapping method with functions in tests.
  4. Easily result handling.
  5. Less code. A little bit :D

Happy coding and testing! #_#

--

--