通过使用suspend关键字用协程来改造2.6 版本后的Retrofit,减少模板代码,加速业务开发

因为Retrofit自 2.6 版本后,原生支持协程, Retrofit 使用协程改造过后,能有效的精简业务代码,进而加速开发进度;

今天对相关代码进行了改造,现做个笔记记录一下

suspend改造前代码:

    @GET("/abc/test/demo")
    fun getListOld(@Query("ver") ver: String?): Call<MyResponse>

使用示例代码:

    @Test
    fun testGetList(){
        val context = InstrumentationRegistry.getInstrumentation().targetContext
        val ver = "ver_123"
        val call =  MyService.getDemo().getList(ver)
        call.enqueue(object : Callback<MyRespose> {
            override fun onResponse(call: Call<MyRespose>, response: Response<MyRespose>) {
                LogUtils.log(context, " response.raw().toString = ${response.raw().toString()}    ${response.raw().headers.toString()}")
                var value = response.body()?.value
                LogUtils.log(context, "onResponse value = ${value }")
            }

            override fun onFailure(call: Call<MyRespose>, t: Throwable) {
                t.printStackTrace()
                LogUtils.log(context, "onFailure ${t.message}")
            }

        });
    }

suspend改造后代码:

    @GET("/abc/test/demo")
    suspend fun getList(@Query("ver") ver: String?): Response<MyResponse>

调用代码的示例:

 @Test
    fun test_getListSuspend(){
        val context = InstrumentationRegistry.getInstrumentation().targetContext

        LogUtils.log(context, "test_getListSuspend")
        val scope = CoroutineScope(Dispatchers.IO)
        val coroutineJob = scope.launch{
            LogUtils.log(context, "coroutineJob .launch")
            val response = MyService.getDemo().getList("ver_123")
            LogUtils.log(context, "response = $response")
            scope.cancel()
        }


    }

可以用来刷新界面的协程代码片段

 

var job: Job? = null;
            job = MainScope().launch {
                Log.d("demo","---start---")
                val response = MyService.getDemo().getList("ver_123").getList("ver_123")
                
                val view:TextView = TextView(context)
                view.textSize = 26f
                view.text = response.raw().toString()
                (context.window.decorView as ViewGroup).addView(view)

                Log.d("demo","---end---")

                job?.run {
                    this.cancel()
                }
            };

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值