【问题标题】:How to make a request with a param using Retrofit and coroutines如何使用 Retrofit 和协程使用参数发出请求
【发布时间】:2020-10-08 11:15:31
【问题描述】:

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

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

【问题讨论】:

    标签: android coroutine kotlin-coroutines retrofit2.6


    【解决方案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
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-27
      • 2017-02-25
      • 2015-07-22
      • 2019-12-04
      相关资源
      最近更新 更多