Our team is using ViewModel
and LiveData
components in developing the current Application. In one of the scenarios on a Button
click, we are initiating a network API call.
The Repository
returns a LiveData
whenever the API results are available.
In the ViewModel
we attach the Observer
only when the Button
is clicked and since we are in ViewModel
we are using observeForever()
This is the code;
//ViewModel Code
//Api Observer
var apiObserver: Observer<ApiState> =
Observer { response ->
when (response.currentState) {
StateConstants.STATE_API_CALLED -> showLoading()
StateConstants.STATE_API_COMPLETE -> stopLoading()
StateConstants.STATE_DATA_LOADED -> processResponseData(response.data)
StateConstants.STATE_API_ERROR -> showError(response.errorMessage)
}
}
fun sendReminderToCustomer() { //This method is called on Button click from XML
repo.apiStateLiveData.observeForever(apiObserver) //attach Observer and Observe Forever
repo.sendReminderDetails() //make api call
}
override fun onCleared() {
super.onCleared()
repo.apiStateLiveData.removeObserver(apiObserver) //remove Observer
}
Since on every button click, we are attaching the same observer to the LiveData
will there be any unknown side effects like,
- Will the same observer get added to
LiveData
observer list multiple times? - If the same observer is added multiple times will the
onChanged()
method get called multiple times too?