从不同的LiveData来源填充适配器

时间:2019-01-28 13:53:24

标签: android android-recyclerview android-room android-livedata android-viewmodel

我玩LiveData并希望了解它能做什么。 我想通过开关(如果需要,使用过滤器)将来自不同来源的数据填充到我的RecyclerView中。

过滤的适配器内的值是不是一个选项。 因此,我决定在视图模型中使用 MediatorLiveData

道:

@Query("SELECT * FROM tasks WHERE completed = 0")
LiveData<List<Task>> getActiveTasksLiveData();

@Query("SELECT * FROM tasks")
LiveData<List<Task>> getAllTasksLiveData();

@Query("SELECT * FROM tasks WHERE completed = 1")
LiveData<List<Task>> getClosedTasksLiveData();

回购:

    public LiveData<List<Task>> getActiveTasks() {
        return mTaskDao.getActiveTasksLiveData();
    }

    public LiveData<List<Task>> getAllTasks() {
        return mTaskDao.getAllTasksLiveData();
    }

    public LiveData<List<Task>> getClosedTasks() {
        return mTaskDao.getClosedTasksLiveData();
    }

ViewModel

public class MainViewModel extends AndroidViewModel {

    private final String TAG = "MainViewModel";

    private final AppDataRepository mData;

    private MediatorLiveData<List<Task>> mMediatorTasks;

    public MainViewModel(@NonNull Application application) {
        super(application);

        mData = AppDataInjector.getDataRepository(application.getApplicationContext());

        mMediatorTasks = new MediatorLiveData<>();
        mMediatorTasks.setValue(null);
    }

    public LiveData<List<Task>> getTasks(){
        return mMediatorTasks;
    }

    public void changeTasksOption(int index){
        mMediatorTasks.removeSource(mData.getAllTasks());
        mMediatorTasks.removeSource(mData.getActiveTasks());
        mMediatorTasks.removeSource(mData.getClosedTasks());
        if (index == R.id.navigation_all){
            Log.i(TAG, "Add source: all");
            mMediatorTasks.addSource(mData.getAllTasks(), new Observer<List<Task>>() {
                @Override
                public void onChanged(List<Task> tasks) {
                    Log.i(TAG, "Add source: all - setValue");
                    mMediatorTasks.setValue(tasks);
                }
            });
        } else if (index == R.id.navigation_closed){
            Log.i(TAG, "Add source closed");
            mMediatorTasks.addSource(mData.getClosedTasks(), new Observer<List<Task>>() {
                @Override
                public void onChanged(List<Task> tasks) {
                    Log.i(TAG, "Add source: closed - setValue");
                    mMediatorTasks.setValue(tasks);
                }
            });
        } else {
            Log.i(TAG, "Add source active");
            mMediatorTasks.addSource(mData.getActiveTasks(), new Observer<List<Task>>() {
                @Override
                public void onChanged(List<Task> tasks) {
                    Log.i(TAG, "Add source: active - setValue");

                    mMediatorTasks.setValue(tasks);
                }
            });
        }
    }
}

片段

    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);

        mNavigationView = view.findViewById(R.id.navigation);
        mFab = view.findViewById(R.id.fabMain);
        mRecyclerView = view.findViewById(R.id.mainRecyclerView);

        tasksAdapterLive = new TasksAdapterLive(mAdapterCallback);
        RecyclerView.LayoutManager manager = new GridLayoutManager(getContext(), 1);
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setAdapter(tasksAdapterLive);

        // set up bottom navigation listener
        mNavigationView.setOnNavigationItemSelectedListener(item -> {
            mViewModel.changeTasksOption(item.getItemId());
            return true;
        });

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(MainViewModel.class);

        mViewModel.getTasks().observe(this, tasks -> {
            if (tasks != null) {
                tasksAdapterLive.setTasks(tasks);
                tasksAdapterLive.notifyDataSetChanged();
            }
        });

        mViewModel.changeTasksOption(mNavigationView.getSelectedItemId());
    }

如您所见,我决定在视图模型中使用 MediatorLiveData 。 我的主要目标-从片段调用 changeTasksOption()时,更改适配器内的数据。

我使用removeSource(),因为我所理解它消除LiveData从观察源。 但是,就我而言,不是。

当我启动应用程序,日志:

MainViewModel: Add source active
MainViewModel: Add source: active - setValue

当我尝试切换到另一个源 - 日志

MainViewModel: Add source: all
MainViewModel: Add source: all - setValue
MainViewModel: Add source: active - setValue
MainViewModel: Add source: all - setValue
MainViewModel: Add source: active - setValue
*** repeats about 100 times

RecyclerView闪烁

所以,请问。 我究竟做错了什么? 我是否误解了文档? 真正的removeSourse()作用是什么? 因为在我的情况下,它不会删除源。

万一我的实现方法错误,您如何建议我这样做?

谢谢!

EDTITED:

经历过了几个我发现溶液小时后。是的,这很糟糕(也许不是吗?)。但显然,这不是普遍的,因为我们不使用罗姆+ LiveData

创建正常间函数返回列表

@Query("SELECT * FROM tasks WHERE completed = 0")
List<Task> getActiveTasks();

@Query("SELECT * FROM tasks")
List<Task> getAllTasks();

@Query("SELECT * FROM tasks WHERE completed = 1")
List<Task> getClosedTasks();

创建MutableLiveData在回购

private MutableLiveData<List<Task>> mTasksTestActive, mTasksTestAll, mTasksTestClosed;

添加theese功能回购

public LiveData<List<Task>> getActiveTasksTest() {
    Executors.newSingleThreadExecutor().execute(() -> {
        List<Task> taskList = mTaskDao.getActiveTasks();
        mTasksTestActive.postValue(taskList);
    });
    return mTasksTestActive;
}

public LiveData<List<Task>> getAllTasksTest() {
    Executors.newSingleThreadExecutor().execute(() -> {
        List<Task> taskList = mTaskDao.getAllTasks();
        mTasksTestAll.postValue(taskList);
    });
    return mTasksTestAll;
}

public LiveData<List<Task>> getClosedTasksTest() {
    Executors.newSingleThreadExecutor().execute(() -> {
        List<Task> taskList = mTaskDao.getClosedTasks();
        mTasksTestClosed.postValue(taskList);
    });
    return mTasksTestClosed;
}

ViewModel更改:

public void changeTasksOption(int index) {
    mMediatorTasks.removeSource(mData.getAllTasksTest());
    mMediatorTasks.removeSource(mData.getActiveTasksTest());
    mMediatorTasks.removeSource(mData.getClosedTasksTest());
    if (index == R.id.navigation_all) {
        Log.i(TAG, "Add source: all");
        mMediatorTasks.addSource(mData.getAllTasksTest(), tasks -> {
            Log.i(TAG, "Add source: all - postValue");
            mMediatorTasks.postValue(tasks);
        });
    } else if (index == R.id.navigation_closed) {
        Log.i(TAG, "Add source closed");
        mMediatorTasks.addSource(mData.getClosedTasksTest(), tasks -> {
            Log.i(TAG, "Add source: closed - postValue");
            mMediatorTasks.postValue(tasks);
        });
    } else {
        Log.i(TAG, "Add source active");
        mMediatorTasks.addSource(mData.getActiveTasksTest(), tasks -> {
            Log.i(TAG, "Add source: active - postValue");

            mMediatorTasks.postValue(tasks);
        });
    }
}

而现在,通过切换UI,我有我的结果。没有更多的循环,一切似乎都正常。

但仍然!这是一个不好的解决方案。房间可能有问题吗?

2 个答案:

答案 0 :(得分:1)

public void changeTasksOption(int index){
    mMediatorTasks.removeSource(mData.getAllTasks());
    mMediatorTasks.removeSource(mData.getActiveTasks());
    mMediatorTasks.removeSource(mData.getClosedTasks());

不,这不是应该的!

所选选项应位于LiveData中。然后就可以使用Transformations.switchMap {针对LiveData来选择正确的LiveData<List<Task>>

private MutableLiveData<Integer> mSelectedIndex = new MutableLiveData<>();

private final LiveData<List<Task>> mMediatorTasks = Transformations.switchMap(mSelectedIndex, (index) -> {
    if (index == R.id.navigation_all) {
        return mData.getAllTasksTest();
    } else if (index == R.id.navigation_closed) {
        return mData.getClosedTasksTest();
    } else {
        return mData.getActiveTasksTest();
    }
});

public void changeTasksOption(int index) {
    mSelectedIndex.setValue(index);
}

public LiveData<List<Task>> getTasks(){
    return mMediatorTasks;
}

此外,你应该把你的mData.get*()方法来回报LiveData<List<Task>>从DAO再次,这是一个更好的解决方案。

答案 1 :(得分:0)

您正在使用先前的回购代码从回购中同步返回值-

public LiveData<List<Task>> getActiveTasks() {
    return mTaskDao.getActiveTasksLiveData();
}

public LiveData<List<Task>> getAllTasks() {
    return mTaskDao.getAllTasksLiveData();
}

public LiveData<List<Task>> getClosedTasks() {
    return mTaskDao.getClosedTasksLiveData();
}

因此,当您调用removeSource(mData.getAllTasksTest())时,它将同步地从存储库中获取数据,这就是为什么您要从所有存储库中接收数据的原因。

在编辑后的代码中,您正在使用辅助线程来获取数据,这意味着您的源实时数据在调解器返回任何值之前已从调解器实时数据中删除。