简体   繁体   English

Room android LiveData 仅观察调用 2 次

[英]Room android LiveData observe call only 2 times

I have a problem using LiveData in Room library android.我在 Room 库 android 中使用 LiveData 时遇到问题。

I have a Fragment where there is a RecyclerView and to populate use LiveData with Observer我有一个片段,其中有一个RecyclerView并使用LiveData填充Observer

mDB.user().getUsers().observe(getViewLifecycleOwner(), new Observer<List<UserModel>>() {
        @Override
        public void onChanged(List<UserModel> userModels) {
            updateUI(userModels);
        }
});

If I click on ADD button, call a startActivity , open a new Activity with my form, compile all fields and @INSERT a new item on DB如果我点击 ADD 按钮,调用一个startActivity ,用我的表单打开一个新的 Activity,编译所有字段并@INSERT在 DB 上@INSERT一个新项目

AsyncTask.execute(() -> {
        mDB.user().addUser("NAME");
        finish();
});

When finish the current Activity, show again previous Fragment and automatically should be call the onChanged .完成当前 Activity 后,再次显示前一个 Fragment 并自动调用onChanged The observe is called only for 2 times, than, if I click on ADD button (for 3th time) and come back to the fragment, never call and never refresh my list. observe仅被调用 2 次,如果我单击 ADD 按钮(第三次)并返回到片段,则永远不会调用并且永远不会刷新我的列表。 I don't know why.我不知道为什么。

I tried with observeForever without results.我试过observeForever没有结果。

I see that in debug, never called removeObserver , so the observer is active.我看到在调试中,从未调用过removeObserver ,因此观察者处于活动状态。

These are my dependencies这些是我的依赖项

def room_version = "2.2.5"
def lifecycle_version = "2.3.0-alpha01"

// Room database
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-service:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version"

You should call observe() from onResume() of UsersFragment , instead of onCreateView() because for adding a new user, you are switching to a new Activity which pauses the current activity and the fragments attached to it instead of destroying the views of the fragments.您应该从UsersFragment onResume()调用observe()而不是onCreateView()因为为了添加新用户,您正在切换到一个新的 Activity 暂停当前活动和附加到它的片段而不是破坏视图碎片。 So, when you come back to the current activity, onCreateView() of UsersFragment never gets called, onResume() is called however.因此,当您返回当前活动时,永远不会调用UsersFragment onCreateView()UsersFragment会调用onResume()

I would, however, suggest you to implement a proper ViewModel , Repository pattern for communicating with Room database.但是,我建议您实现一个适当的ViewModelRepository模式来与Room数据库进行通信。

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

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