Home > Mobile >  Mutable live-data give multiple response give old response from api and after give new response
Mutable live-data give multiple response give old response from api and after give new response

Time:11-30

**Mutable live-data give multiple response old response from api and after give new response **

mutable live-data give multiple response

here is my code

Repository

suspend fun forgotPassword(email:String,sig: String,salt: String):Response<ForgotDataClass>{
    return RetrofitInstance.api.forgotPassword(email,sig,salt)
}

View model

class ForgotPasswordViewModel(private val repository: Repository) : ViewModel() {

var myPassword: MutableLiveData<Response<ForgotDataClass>> = MutableLiveData()
fun forgotPassword(email: String, sig: String, salt: String) {
    viewModelScope.launch {
        val response = repository.forgotPassword(email, sig, salt)
        myPassword.value = response
    }
}

}

api interface

@POST("forgot_password.php")
 suspend fun forgotPassword(
    @Query("email") email:String,
    @Query("sig") sig:String,
    @Query("salt") salt:String
):Response<ForgotDataClass>

main activity

viewModel.forgotPassword(email,sig1,salt1)
                    viewModel.myPassword.observe(this, { response ->
                        if (response.isSuccessful){
                            when(response.body()?.status){
                                "1" -> {
                                    finish()
                                    Toast.makeText(this, "your password reset successfully", Toast.LENGTH_SHORT).show()
                                }
                                "-2" -> {
                                    Toast.makeText(this, "Email is not exit ", Toast.LENGTH_SHORT).show()
                                }
                                else -> {
                                    Toast.makeText(this, "Try again something went wrong", Toast.LENGTH_SHORT).show()
                                }
                            }
                        } else {
                            Toast.makeText(this, "Try again something went wrong", Toast.LENGTH_SHORT).show()
                        }

CodePudding user response:

You can try this. You can return your LiveData like this and I don't think you need a global variable. And use postValue when using a different thread to update you MutableLiveData

class ForgotPasswordViewModel(private val repository: Repository) : ViewModel() {

    fun forgotPassword(email: String, sig: String, salt: String): LiveData {
        var myPassword = MutableLiveData<Response<ForgotDataClass>>()
        viewModelScope.launch {
            myPassword.postValue(repository.forgotPassword(email, sig, salt))
        }
    }
   return myPassword
}

In your fragment/activity you can call like this

viewModel.forgotPassword(email,sig1,salt1).observe(this) { response ->
    // do stuff with your result
}
  • Related