0

我是协程的新手,我试图弄清楚如何使用改造提出一个简单的请求,我可以在其中传递我的自定义参数。所有赞扬它多么简单的示例都使用硬编码的查询参数或根本不使用它们的调用(即https://proandroiddev.com/suspend-what-youre-doing-retrofit-has-now-coroutines -support-c65bd09ba067 )

我的场景如下 - 片段有一个编辑文本,用户在其中放置数据,片段也观察 ViewModel 中定义的 MutableLiveData。在按下按钮时,我想使用来自 edittext 的值进行查询,并使用响应内容更新 MutableLiveData。这听起来并不复杂,但找不到使用协程的方法。

4

1 回答 1

1

假设您有下一个界面:

interface Webservice {
    @GET("/getrequest")
    suspend fun myRequest(@Query("queryParam1") String param1): Object
}

在您拥有的视图模型中,您可以定义一个将在协程内执行改造调用的方法:

import androidx.lifecycle.Transformations
import kotlinx.coroutines.Dispatchers
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.LiveData

class YourViewModel {

    private val mutableLiveData = MutableLiveData<Object>()
    val liveData = Transformations.map(mutableLiveData) { object ->
            // return object or use it to calculate 
            // new result that will be returned by this liveData object
            // e.g. if object is a List<Int> you can sort it before returning
            object
        }

    companion object {
        // Just for the sake of explaining we init 
        // and store Webservice in ViewModel
        // But do not do this in your applications!!
        val webservice = Retrofit.Builder()
            .baseUrl(Constant.BASE_URL)
            .addConverterFactory(yourConverter)
            .build()
            .create(Webservice::class.java)
    }

    ...

    fun executeNetworkRequest(String text) {
        viewModelScope.launch(Dispatchers.IO) {
            val result = webservice.myRequest(text)

            withContext(Dispatchers.Main) {
                mutableLiveData.value = result
            }
        }
    }
}
于 2020-06-18T12:09:37.197 回答