简体   繁体   English

多次将同一个观察者添加到 LiveData

[英]Add same Observer multiple times to LiveData

Our team is using ViewModel and LiveData components in developing the current Application.我们的团队在开发当前应用程序时使用ViewModelLiveData组件。 In one of the scenarios on a Button click, we are initiating a.network API call.在点击Button的场景之一中,我们发起了一个.network API 调用。

The Repository returns a LiveData whenever the API results are available.只要 API 结果可用, Repository就会返回一个LiveData

In the ViewModel we attach the Observer only when the Button is clicked and since we are in ViewModel we are using observeForever()ViewModel中,我们仅在单击Button时附加Observer ,因为我们在ViewModel中,所以我们使用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,由于在每次单击按钮时,我们都将同一个观察者附加到LiveData是否会有任何未知的副作用,例如,

  1. Will the same observer get added to LiveData observer list multiple times?同一个观察者会被多次添加到LiveData观察者列表中吗?
  2. If the same observer is added multiple times will the onChanged() method get called multiple times too?如果多次添加同一个观察者, onChanged()方法是否也会被多次调用?

Yes and yes.是的,是的。 Be sure to add an observer only once (in your viewModel's init , for example)确保只添加一次观察者(例如,在您的 viewModel 的init中)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM