Reputation: 3018
I am trying to get response into live data from api, but request is not getting called with this code.
class AuthActivityViewModel : ViewModel() {
var authResp: LiveData<ObjAuthResp> = MutableLiveData()
val repository = BaseRepository()
fun login(username: String, password: String) {
authResp = liveData(Dispatchers.IO) {
val resp = repository.login(username, password)
emit(resp)
}
}
}
but it works with this code.
class AuthActivityViewModel : ViewModel() {
val repository = BaseRepository()
var authResp = liveData(Dispatchers.IO) {
val resp = repository.login(username, password)
emit(resp)
}
}
API service
@POST("profile/pub/auth/login")
suspend fun login(@Body authReqBody : ObjAuthReqBody): ObjAuthResp
BaseRepository
open class BaseRepository {
suspend fun login(username:String,password:String) = service.login(ObjAuthReqBody( username, password))
}
Calling from activity
btn_login.setOnClickListener {
viewModel.login(edt_username.text.toString(),
edt_password.text.toString())
}
Upvotes: 3
Views: 1461
Reputation: 3018
Answering my own question,
the problem was in line authResp = liveData(Dispatchers.IO) {...
this was creating new LiveData while the old observers where observing the initial var authResp: LiveData<ObjAuthResp> = MutableLiveData()
. So, as there is no Observers listening to the newly created LiveData
the call is not even being made.
This code is working
var authResp = MutableLiveData<ObjAuthResp>()
fun login(username: String, password: String) {
viewModelScope.launch {
withContext(Dispatchers.IO) {
val resp = repository.login(username, password)
authResp.postValue( resp)
}
}
}
Upvotes: 2