0

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,

  1. Will the same observer get added to LiveData observer list multiple times?
  2. If the same observer is added multiple times will the onChanged() method get called multiple times too?
iCantC
  • 2,852
  • 1
  • 19
  • 34
  • 1
    take a look at this topic, maybe it helps https://stackoverflow.com/questions/59107330/is-observeforever-lifecycle-aware – Jassem Ben Hamida May 18 '20 at 08:12
  • Pretty much every time I had idea to "observeForever" in view model it turned out to be bad idea that had to be refactored. – ror May 19 '20 at 14:21

1 Answers1

0

Yes and yes. Be sure to add an observer only once (in your viewModel's init, for example)

Alex Timonin
  • 1,872
  • 18
  • 31