如何在后台线程完成后正确更新MutableLiveData?

问题描述 投票:0回答:1

一旦更新MutableLiveData对象,我将无法显示我的RecyclerView项目。

创建ViewModel时,将实例化MutableLiveData对象,并将其值设置为存储库函数的返回值(在后台线程上运行网络任务)。更改对象后,片段将使用新数据设置RecyclerView适配器。

ViewModel

private MutableLiveData<List<GetMemberUnitsMutation.Get_member_unit>> mUnits;

public OrganizationsViewModel(String memberID) {
    mUnits = new MutableLiveData<>();
    mUnits.setValue(organizationsRepository.getMemberUnits(memberID));
}

FragmentActivity

organizationsViewModel.getmUnits().observe(getViewLifecycleOwner(), new Observer<List<GetMemberUnitsMutation.Get_member_unit>>() {
    @Override
    public void onChanged(List<GetMemberUnitsMutation.Get_member_unit> memberUnits) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressBar.setVisibility(View.GONE);
                recyclerView.setAdapter(new OrganizationsAdapter(memberUnits));
            });
        }
    }
});

问题是onChanged在线程完成之前被触发,为我的适配器返回一个空值。仅在线程完成并重新创建视图后,它才能正确显示项目。

android android-livedata mutablelivedata
1个回答
0
投票

解决方案很简单。我必须将活动和MutableLiveData对象传递到存储库,并在onStatusEvent函数(相当于AsyncTask的onPostExecute)中更新UI线程上的数据。

public OrganizationsViewModel(FragmentActivity activity, String memberID) {
    organizationsRepository.getMemberUnits(activity, mUnits, memberID);
}

@Override
public void onStatusEvent(@NotNull ApolloCall.StatusEvent event) {
    super.onStatusEvent(event);
    if (event == ApolloCall.StatusEvent.COMPLETED) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mUnits.setValue(memberUnits);
            }
        });
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.