【问题标题】:When will retrofit add call adapter factory support for coroutine just like Rx officially? [closed]Retrofit 什么时候会像 Rx 一样正式添加协程的调用适配器工厂支持? [关闭]
【发布时间】:2020-03-31 04:17:58
【问题描述】:

我已经使用 Retrofit 大约 3 年了,自从引入 RxAndroid 以来,square up 添加了一个转换器工厂来简化对 RxStream 的响应。现在我没有看到 Coroutines 的任何官方添加。虽然我发现了一个由 Jake Wharton 开发的带有转换器的实验套件,但我真的怀疑它在现场项目中的可靠性。

有什么想法吗?

实现 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-experimental-adapter:1.0.0'

【问题讨论】:

    标签: kotlin retrofit kotlin-coroutines


    【解决方案1】:

    目前 Retrofit 内置了暂停功能,因此您不再需要将其作为延迟返回。只返回真实的元数据。像这样

    @GET("/users")
    suspend fun getUsers(): List<Users>
    

    或者,你想在https://s.id/kotlin-add阅读我的演讲

    【讨论】:

      【解决方案2】:

      Retrofit 2.6.0 中添加了协程支持

      在 app.gradle 中

      def retrofitVersion = '2.6.0'
      implementation "com.squareup.retrofit2:retrofit:$retrofitVersion"
      

      API 服务接口

       @GET("api/?")
      suspend fun getImages(
          @Query("key") apiKey: String,
          @Query("q") query: String,
          @Query("image_type") imageType: String,
          @Query("pretty") yesOrNo: Boolean
          ):ApiResponse
      
      

      这不是正确的方法,只是一个例子

      fun getImagesForPicassoView() {
              CoroutineScope(Dispatchers.IO).launch {
                  apiResponse.postValue(apiService.getImages(Constants.API_KEY,"food","photo",true))
              }
          }
      

      【讨论】:

        【解决方案3】:

        根据this 文章Retrofit 已经支持协程。没有吗?为了找到它,你不能花 5 秒钟而不是在这里写一个问题吗?!

        只需在您的 Retrofit 接口中创建挂起方法并直接返回您的数据对象。

        @GET("api/todo")
        suspend fun getTodo(@Path(value = "id") todoId: Int): Todo
        

        在链接中阅读更多内容。

        【讨论】:

        • 我在询问 callAdapterFactory。您的回答与我的问题无关
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-09-09
        • 1970-01-01
        • 2011-05-18
        • 1970-01-01
        • 1970-01-01
        • 2018-07-09
        • 1970-01-01
        相关资源
        最近更新 更多