Leave a rating/review
Retrofit has built-in support for couroutines. Lets see how you can use this support to simplify your code further.
Demo
This demo will be super short, but also very sweet in that manner! :] Open RemoteApiService.kt. Change the deleteNote API call to the following:
suspend fun deleteNote(@Query("id") noteId: String): DeleteNoteResponse
Not a big change in terms of code, but a huge change when it comes to development! You added a suspend modifier to the function. This will communicate to Retrofit, to generate the appropriate code for threading, like the Dispatchers.IO usage.
You also removed the Call/Response part of the return type, and are just returning the model.
This is possible because once again, using coroutines and generated code, Retrofit knows how to give you what you need, in this case, a DeleteNoteResponse.
Head over to the RemoteApi.kt file, to finish up this refactoring.
Change the code in deleteTask() to the following:
suspend fun deleteTask(taskId: String) = try {
val data = apiService.deleteNote(taskId)
Success(data.message)
} catch (error: Throwable) {
Failure(error)
}
Because Retrofit is now taking care of threading, you don’t need the withContext or the dispatchers pieces of code. And you can return the try/catch block, as an expression.
Notice how you don’t need to check the response body, you immediately receive the data from the API, or the request just fails, and you get an error! If you’re looking for what to do next, there isn’t anything! :]
This is it. Run the project, and try to delete a task once more. Everything will work as before, with a lot less code than what you first had with HTTP connections, or with Retrofit.
Lecture 2
This is why coroutines are so awesome! :] They are super easy to use, easy to understand, for at least the fundamental concepts, and they take care of a lot of things, like threading, instead of you. In the next episode, you’ll refactor the rest of the API calls, to rely on coroutines! :] See you there!