【问题标题】:How to correctly use suspend fun in Retrofit 2.6.0 coroutines with kotlin如何在带有 kotlin 的 Retrofit 2.6.0 协程中正确使用暂停乐趣
【发布时间】:2020-01-04 16:59:36
【问题描述】:

我正在尝试编写我的网络请求以使用 Retrofit 2.6.0 和协程暂停乐趣。但我不断得到空对象。这是我第一次尝试改造 2.6 和协程

这是我的示例代码

数据类

data class ProjectList (val data: List<Project>)

示例 JSON 对象

{
    "data": [
        {
            "project_id": "10824",
            "project_name": "Bendor Project",
            "project_number": "P010824",
            "content_items": [
                {
                    "content_id": "235",
                    "content_name": "Longonot Project",
                    "content_description": "Valves Example ",
                    "content_date_updated": "2019-08-31 12:29:00",
                    "project_id": "10824",
                    "media_items": []


网络接口

    suspend fun getProjects(@Query("mode") mode: String): ProjectList

改造客户端

class RetrofitClient{


    private val gson = GsonBuilder()
        .setLenient()
        .create()


    private fun retrofit(): Retrofit = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build()

    val retrofitService: ProjectAPI by lazy {
        retrofit().create(ProjectAPI::class.java)
    }

存储库

class ProjectRepository {

    private val client: ProjectAPI = RetrofitClient().retrofitService

    suspend fun getProjectData(mode : String) : ProjectList = client.getProjects(mode)

}

ViewModel 中的实时数据

val request : LiveData<ProjectList> = liveData(Dispatchers.IO){
            val response = repository.getProjectData(SOURCE_MODE)
            Log.e(TAG, "${response.data}")
            emit(response)
        }

我不断收到空响应。我哪里不对?

【问题讨论】:

  • 看起来你做的一切都是正确的。能否将类型更改为Response&lt;ProjectList&gt; 并调试请求以查看请求是否与您要发送的内容匹配?
  • 我刚刚替换了这个val request : LiveData&lt;ProjectList&gt; = liveData(Dispatchers.IO){ val response = repository.getProjectData(SOURCE_MODE) Log.e(TAG, "${response.data}") emit(response) } ``` viewModelScope.launch(Dispatchers.IO){ val response = repository.getProjectData("main") Log.e(TAG, "${response. data}") liveProjectData.postValue(response.data) }``` 试图找出差异
  • 先分享项目类
  • 你可能在解析时做错了
  • 我的另一个观点是你不需要发出值,只需调用suspend func。然后在您的 ViewModel 中创建 LiveData 并最后调用 livedata.post() 以便能够将网络响应分配给您的 LiveData

标签: kotlin coroutine kotlin-coroutines suspend retrofit2.6


【解决方案1】:

您不需要发出值,只需在协程范围内调用您的suspend func,然后在您的ViewModel 中创建一个新的LiveData,最后调用 liveData.post() 以便能够分配网络请求对您的LiveData 对象的响应。

【讨论】:

    猜你喜欢
    • 2019-11-22
    • 2019-05-20
    • 2018-08-14
    • 2019-12-10
    • 2020-04-05
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多