'How to send parameters for get request using retrofit and kotlin Coroutines.?
I was following the tutorial from https://proandroiddev.com/suspend-what-youre-doing-retrofit-has-now-coroutines-support-c65bd09ba067. I am having difficulty to understand how to send parameters to get request from MainActivity
Webservice.kt
interface Webservice {
@GET("/todos/{id}")
suspend fun getTodo(@Path(value = "id") todoId: Int): Todo
}
TodoRepository.kt
class TodoRepository {
var client: Webservice = RetrofitClient.webservice
suspend fun getTodo(id: Int) = client.getTodo(id)
}
MainViewModel.kt
class MainViewModel : ViewModel() {
val repository: TodoRepository = TodoRepository()
val firstTodo = liveData(Dispatchers.IO) {
val retrivedTodo = repository.getTodo(1)
emit(retrivedTodo)
}
}
MainAcitvity.kt
class MainActivity : AppCompatActivity() {
lateinit var viewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
showFirstTodo()
}
private fun showFirstTodo() {
viewModel.getFirstTodo().observe(this, Observer {
titleTextView.text = it.title
})
}
}
Solution 1:[1]
You can change your viewModel code something like this
private val _todo = MutableLiveData<Todo>()
val todo : LiveData<Todo> get() =_todo
//Call this method from activity
fun getTodo(arg : Int)
{
val result = //Call Coroutines here
_todo.postValue(result)
}
Solution 2:[2]
There is a difference between Path
and Query
in GET
request.
You can easily pass query string like this:
interface Webservice {
@GET("/todos/{id}")
suspend fun getTodo(@Path(value = "id") todoId: Int, @Query("name") name: String?): Todo
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | m3g4tr0n |
Solution 2 | ?????? |