0

Im new to coroutines and Im trying to figure out how to make a simple request using retrofit, where I can pass my custom param. All the examples which praise how simple it is use either hardcoded query parameter or make calls which don't use them at all (i.e. https://proandroiddev.com/suspend-what-youre-doing-retrofit-has-now-coroutines-support-c65bd09ba067)

My scenario is as follows - fragment has an edit text where user puts data and also fragments observes a MutableLiveData that's defined in ViewModel. On button press I want to make a query using value from the edittext and update the MutableLiveData with the response content. It doesn't sound complicated but can't find a way to do it with coroutines.

shtas
  • 499
  • 2
  • 17

1 Answers1

1

Let's imagine you have next interface:

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

Inside a view model that you have you can define a method that will execute retrofit call inside a coroutine:

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
            }
        }
    }
}
Jenea Vranceanu
  • 4,530
  • 2
  • 18
  • 34