简体   繁体   English

当我更改 LiveData 的观察者时会发生什么

[英]What happens when i change the observer of a LiveData

What happens if I have a ViewModel that observes some LiveData With the following line of code如果我有一个使用以下代码行观察一些 LiveData 的 ViewModel 会发生什么

myViewModel.getData.observe(getViewLifeCycle(),Observer);

what if I have anther LiveData data2 inside my view model and I started observing this data.如果我的视图 model 中有另一个 LiveData data2 并且我开始观察这些数据怎么办。

myViewModel.getData2.observe(getViewLifeCyle(),Observer);

what happens for the first observer?第一个观察者会发生什么? is that considered to be a memory leak?这是否被认为是 memory 泄漏? should I remove all the observers on the data before I go observing anther data?在我 go 观察花药数据之前,我应该删除数据上的所有观察者吗?

EDIT: I have the following code for a SearchBar that I use to Observe the data from Room Database.编辑:我有一个 SearchBar 的以下代码,用于观察房间数据库中的数据。

@Override
            public boolean onQueryTextChange(String s) {
                String query =  "%" + s + "%";
                Log.d(TAG, "onQueryTextChange: " + query);
                problemViewModel.getProblemsByQuery(query).observe(getViewLifecycleOwner(),observer);
                return true;
            }
                
                    

I'm concerned with this line.我很关心这条线。

problemViewModel.getProblemsByQuery(query).observe(getViewLifecycleOwner(),observer);

I repeat it over and over inside the method whenever the text changes.每当文本发生变化时,我都会在方法中一遍又一遍地重复它。 so will that cause a problem?那么这会导致问题吗?

There is no leak immediately visible here.这里没有立即可见的泄漏。 You can certainly observe as many LiveData as you want simultaneously - as many as you can fit into memory.您当然可以同时观察尽可能多的 LiveData - 尽可能多地放入 memory。 And they can all share the same observer object, if that's what you want.如果你想要的话,他们都可以共享同一个观察者 object。

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

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