Home » Android » android – kotlin – mvvm – posting data to webservice-Exceptionshub

android – kotlin – mvvm – posting data to webservice-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

I want to post some data to webservice and get the result . this is my code :

fab.setOnClickListener {
 viewModel.newBimeGozar(name)
                    .observe([email protected], Observer {
                        dialogbimegozarNew?.hidePg()
                    })
}

this is my viewmodel :

class BimeNewViewModel:ViewModel() {
private val repository=BimeNewRepository()

fun newBimeGozar(name: String): MutableLiveData<StatModel> {
    return repository.newBimeGozar(name)
}

this is my repository :

fun newBimeShode(
    name: String
): MutableLiveData<StatModel> {
    scope.launch {
        val request = api.newBimeShode(name)
        withContext(Dispatchers.Main) {
            try {
                val response = request.await()
                regBimeshodeLiveData.value = response
            } catch (e: HttpException) {
                Log.v("this", e.message);
            } catch (e: Throwable) {
                Log.v("this", e.message);
            }
        }
    }
    return regBimeshodeLiveData;
}

it works fine but there is a problem . I think the observer keeps running and if the result’s answer is an error and user press fab button again , it creates a new observer and after this , it returns two value , the first value is the first run and the second value is the second run

how can I fix this ? what is the correct way for submitting forms ?

How to&Answers:

If your problem is because of LiveData, you should use SingleLiveEvent like as follow

// For first article
val _liveData = MutableLiveData<Event<StatModel>>()

// For second article
val _liveData = SingleLiveEvent<StatModel>()

If you do not know SingleLiveEvent, you can find it here and here.

If your problem is because of your ui element, I think the best solution is to disable the submit button after submitting for the first time.