前情提要:很简单的用法,没啥可补充的,英文也很简单,自己看吧。
Suspend what you’re doing: Retrofit has now Coroutines support!
It official now! Retrofit 2.6.0 has been released with support for suspend functions.
This allows you to express the asynchrony of HTTP requests in an idiomatic惯用的 fashion for the Kotlin language.
Behind the scenes this behaves as if defined as
fun user(...): Call<User>
and then invoked withCall.enqueue
. You can also returnResponse<User>
for access to the response metadata.
To better understand how this works and how to migrate your current code (I know you will, just come back here when you notice how coincise and simple is the new syntax at the end of the post) let’s make an example app that… makes a simple network request!
In this example, we’ll use JSONPlaceholder, a fake REST API that’s very useful when you need a way to quickly test network requests.
We’ll use the /todos endpoint, that returns the json of a simple Todo object.
For reference:
GET https://jsonplaceholder.typicode.com/todos/1
will return:
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
Test project set up
First of all, let’s configure Retrofit and the environment for our test. If you’re in an hurry, feel free to skip this part and go directly to the next paragraph.
First the only POJO we need is the data class for a single Todo:
data class Todo(
val id: Int = 0,
val title: String = "",
val completed: Boolean = false
)
Then we write the Retrofit interface. Remember that the fake endpoint is:
GET https://jsonplaceholder.typicode.com/todos/1
So it will be:
interface Webservice {
@GET("/todos/{id}")
fun getTodo(@Path(value = "id&