协程在Retrofit上的使用

前情提要:很简单的用法,没啥可补充的,英文也很简单,自己看吧。

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 with Call.enqueue. You can also return Response<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&
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值