square / retrofit

A type-safe HTTP client for Android and the JVM
https://square.github.io/retrofit/
Apache License 2.0
43.08k stars 7.31k forks source link

Documentation request for coroutines and Retrofit #3263

Open eothein opened 4 years ago

eothein commented 4 years ago

It would be nice if the official documentation explains how to use Retrofit together with co-routines together with the best practices regarding the asynchronous handling of requests. My students need to implement their calls using Retrofit and co-routines (following the tutorials in the Udacity course, but for documentation I'm relying on (not always the best) medium articles instead of official docs.

Kind regards

Jens

GypsyTheDj commented 4 years ago

Since the release of Retrofit2 version 2.6.0, there has been added native support for co-routines, this helps to achieve better performance and reduces boilerplate significantly. I will show you how to change/implement your repository, view model and the UI controlling activity. Finally I will show you how to handle errors with this new approach.

The main changes that you will need to make is making the co-routine calling functions suspendable, as is required for them to function in their intended manner, i.e by stopping and starting according to the application state.

So in our API interface we make the @GET function a suspend function as shown

Next comes the Repository class which creates the instance of the retrofit service and initiates the API call, our method for this call should be a suspend function as it will later be called through a co-routine.

As you can see the code which was earlier 50–60 lines has been reduced to a very clean single line, as the procedure has been streamlined through the use of a co-routine. The main thing missing from the getData() method is the error handling callback that is automatically created when a call is enqueued.This error can be handled by wrapping the co-routine in a try/catch block. Now that our repository is set up we can create a method in the viewModel which uses the liveData builder to create a process on the IO thread.

Add this viewModel and liveData dependencies for the coroutine to work

The emit function emits the changes in the underlying database to the observer variables, in our case which will be located in the MainActivity.

Here we can see the observer observing the value of aqi from the API and updating the UI accordingly.

That's it! your code has now become significantly cleaner and you have leveraged the power of co-routines.

cc8080 commented 3 years ago

All of the code blocks referred to in the reply are appearing as script src links. The content is not being shown. Too bad, because it looks like just the info I was looking for. @GypsyTheDj: Is there a way to see the code blocks? Thanks!