You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Retrofit中以百分比形式展示Response的获取进度?

需求与示例代码

有时获取JSON格式的响应可能需要几分钟,原因是响应中包含大量对象。我想要实现的是展示响应的获取进度。以下是我简化后的Retrofit获取响应示例代码:

UserApi接口

@GET("users")
@Headers(
    "Accept:$HEADERS_ACCEPT", "Content-Type:$HEADERS_CONTENT_TYPE",
    "Authorization: $AUTHORISATION_TYPE $API_KEY"
)
fun getUsersList(@Query("page") pageNo: String, @Query("per_page") perPageNo: String): Call<List<User>>

Repository实现

override suspend fun getUsersList(pageNo: String , perPageNo: String,
                                  usersLiveData: MutableLiveData<List<User>?>) = withContext(ioDispatcher) {

    val call = retrofitUserApiInstance.getUsersList(pageNo, perPageNo)

    call.enqueue(object : Callback<List<User>> {
        override fun onFailure(call: Call<List<User>>, t: Throwable) {
            usersLiveData.postValue(null)
        }

        override fun onResponse(call: Call<List<User>>, response: Response<List<User>>) {
            if (response.isSuccessful) {
                usersLiveData.postValue(response.body())
            } else {
                usersLiveData.postValue(null)
            }
        }
    })
}

内容的提问来源于stack exchange,提问作者DevPeter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 13:28:13