TIL 5: Made your retrofit rest client reactive a little bit.
Just apply right adapter.
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 CompletableFuture
s:
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:
- All API calls async by default.
- Call will be executed only when you access future data any way. For example
future.get()
orfuture.join()
methods calls. - No need to think about wrapping method with functions in tests.
- Easily result handling.
- Less code. A little bit :D
Happy coding and testing! #_#