如何使用 Retrofit 和协程通过参数发出请求
How to make a request with a param using Retrofit and coroutines
我是协程的新手,我正在尝试弄清楚如何使用改造来发出简单的请求,我可以在其中传递我的自定义参数。所有赞扬它是多么简单的示例都使用硬编码查询参数或进行根本不使用它们的调用(即 https://proandroiddev.com/suspend-what-youre-doing-retrofit-has-now-coroutines-support-c65bd09ba067)
我的场景如下 - 片段有一个编辑文本,用户可以在其中放置数据,片段还观察在 ViewModel 中定义的 MutableLiveData。按下按钮时,我想使用 edittext 中的值进行查询,并使用响应内容更新 MutableLiveData。听起来并不复杂,但找不到用协程来做的方法。
假设您有下一个界面:
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
}
}
}
}
我是协程的新手,我正在尝试弄清楚如何使用改造来发出简单的请求,我可以在其中传递我的自定义参数。所有赞扬它是多么简单的示例都使用硬编码查询参数或进行根本不使用它们的调用(即 https://proandroiddev.com/suspend-what-youre-doing-retrofit-has-now-coroutines-support-c65bd09ba067)
我的场景如下 - 片段有一个编辑文本,用户可以在其中放置数据,片段还观察在 ViewModel 中定义的 MutableLiveData。按下按钮时,我想使用 edittext 中的值进行查询,并使用响应内容更新 MutableLiveData。听起来并不复杂,但找不到用协程来做的方法。
假设您有下一个界面:
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
}
}
}
}