RickAndMorty-AndroidArchitectureSample
RickAndMorty-AndroidArchitectureSample copied to clipboard
Question
sorry it's not an issue, but i really need help for POST method, how can do POST in viewmodel? if i have username and password
I think we can do it with LiveData Transformations. You listen to the changes in the post body and when the body changes Transformation.switchMap() will trigger and it will call the Repository method inside it. There are examples in the Google's advance github browser repo on GitHub.
you can do some thing like this @gilangsatria09 ` data class logedinUserData(var userName:String,var pass:String,var token:String) private val _userData= MutableLiveData<logedinUserData>()
private val _login =_userData.switchMap { userData ->
repository.userLogin(userData.userName,userData.pass,userData.token)
}
val userLoginResponse: LiveData<Resource<UserLoginResponse>> = _login
fun start(userData: logedinUserData) {
_userData.value = userData
}`
I think I have the same problem, I asked a question on stackoverflow
https://stackoverflow.com/questions/68702117/i-have-a-problem-with-the-code-in-viewmodel-kotlin-coroutines-livedata
I think we can do it with LiveData Transformations. You listen to the changes in the post body and when the body changes Transformation.switchMap() will trigger and it will call the Repository method inside it. There are examples in the Google's advance github browser repo on GitHub.
There are examples in the Google's advance github browser repo on GitHub.
Can you post the address of this project? I'll take a look
Hello, I did a post like this and it's working fine so far:
//call
repository.commitChanges( getChangesObject() ).observeForever(commitChangesObserver)
//observer
commitChangesObserver = Observer<ResultClass<ModelClass>> {
if (it is ResultClass.Error)
handleError(it.error)//tested and working
}
//remember to remove observer
override fun onCleared() {
super.onCleared()
repository.commitChanges( getChangesObject() ).removeObserver(commitChangesObserver) //at this point the changes object is empty
}
//Repository
fun commitChanges(changes: LocalClass) = performPostOperation(
networkCall = { remoteDataSource.commitChanges(LocalClass.toModelClass(changes)) }, //the class on DB is not the same needed on the endpoint so we transform it
saveCallResult = { localDataSource.update(LocalClass.fromModel(it)) }//again switch back from model to local class
)
//Strategy utils
fun <A> performPostOperation(
networkCall: suspend () -> ResultClass<A>,
saveCallResult: suspend (A) -> Unit,
) : LiveData<ResultClass<A>> =
liveData(Dispatchers.IO) {
val responseStatus = networkCall.invoke()
if (responseStatus is ResultClass.Success) {
saveCallResult(responseStatus.data)
}
emit(responseStatus)
}
*Notice we don\t listen to success on commitChangesObserver since live data is already being observed (also with observefovever on the viewmodel, whish is also removed oncleared() )