Retrofit2在Kotlin中排队onResponse()

时间:2018-06-08 17:23:24

标签: android kotlin retrofit2

在异步onResponse()中设置data.value之前,函数返回null。 如何让它首先获取数据然后返回该数据?

fun getNews(code: String): LiveData<List<News>>{

    val call = service.getNewsByCountry(code, Constant.API_KEY)

    var data = MutableLiveData<List<News>>()

    call.enqueue(object : Callback<NewsResponse> {
        override fun onFailure(call: Call<NewsResponse>?, t: Throwable?) {
            Log.v("retrofit", "call failed")
        }

        override fun onResponse(call: Call<NewsResponse>?, response: Response<NewsResponse>?) {
            data.value = response!!.body()!!.articles
        }

    })

    return data
}

4 个答案:

答案 0 :(得分:3)

您正在进行异步调用,因此在异步调用解析之前不会设置data.value。但是,由于您正在生成MutableLiveData,您应该能够观察到,当您的异步调用设置值时,它将为您提供更新。

答案 1 :(得分:0)

尝试

fun getNews(code: String): LiveData<List<News>>{

    val call = service.getNewsByCountry(code, Constant.API_KEY)
    var data = MutableLiveData<List<News>>()
    doAsync {
        call.enqueue(object : Callback<NewsResponse> {
            override fun onFailure(call: Call<NewsResponse>?, t: Throwable?) {
                Log.v("retrofit", "call failed")
            }

            override fun onResponse(call: Call<NewsResponse>?, response: Response<NewsResponse>?) {
                data.value = response!!.body()!!.articles
            }

        })
    }

    return data
}

如果不存在doAsync,请尝试在app/build.gralde

上添加关注anko依赖项
implementation "org.jetbrains.anko:anko-design:0.10.5"

答案 2 :(得分:0)

只需使用object:Callback

 accessTocken.enqueue(object : Callback<AccessToken> {
            override fun onFailure(call: Call<AccessToken>, t: Throwable) {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }

            override fun onResponse(call: Call<AccessToken>, response: Response<AccessToken>) {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }

        })

答案 3 :(得分:0)

在这里,我找到了对您在本文中提出的问题的更广泛的回答。

改造 2.6.0 之前,您必须调用 enqueue() 并实施回调。现在没有必要了。

这里有完整的答案 -> https://proandroiddev.com/suspend-what-youre-doing-retrofit-has-now-coroutines-support-c65bd09ba067