Retrofit met Coroutines

Retrofit met Coroutines
Finally the latest version of Retrofit (2.6.0) has got out. While it was already really easy to use and so much fun, Retrofit is now easy…

Finally the latest version of Retrofit (2.6.0) has got out. While it was already really easy to use and so much fun, Retrofit is now easy, fun and shorter to write. Let’s deal with a refactor scenario from the previous version:

Version 2.5.0:

Obviously we have to return the same type until we await() for that response:

Notice we are returning the Deferredtype which holds our response. We won’t stop on what a Deffered is apart from sayin that it’s just a Future.

And when we want to get that response:

Notice we are calling the await() method in order to wait until our asynchronous operation has finished.

Well, no need for that anymore!

Version 2.6.0:

Drop the Deferred type and mark your methods as suspend . Again we wont stop on what suspend methods are apart from saying that it is a way to tell my program that this method is going to be a little late.

And after that, do the same until you await the response:

Now let’s implement the method:

Notice there is no need to await() that method because retrofit does that for you. It will return your defined type.

Note: You should also drop the .addCallAdapterFactory(CoroutineCallAdapterFactory()) from your Retrofit instance build.
I am using GlobalScope because I am not inside a Activity/Fragment/ViewModel which would have theis own lifecycle. Please avoid the GlobalScope . For just an example it’s fine.

Source:

Good luck.