通过观察ViewModel在RecyclerView中搜索PagedList的LiveData

Aha*_*had 8 android searchview android-recyclerview android-viewmodel android-paging

使用 android Paging 库,可以很容易地从数据库中分块加载数据,并且 ViewModel 提供自动 UI 更新和数据保存。所有这些框架模块帮助我们在 Android 平台上创建一个出色的应用程序。

典型的 Android 应用程序必须显示项目列表并允许用户搜索该列表。这就是我想通过我的应用程序实现的目标。所以我通过阅读很多文档、教程甚至stackoverflow的答案来完成了一个实现。但我不太确定我是否做得正确或者我应该如何做。下面,我展示了使用 ViewModel 和 RecyclerView 实现分页库的方法。

请检查我的实施并纠正我的错误或告诉我应该如何做。我认为有许多像我一样的新 Android 开发人员仍然对如何正确执行此操作感到困惑,因为没有单一来源可以回答您关于此类实现的所有问题。

我只展示我认为重要的东西。我正在使用房间。这是我正在使用的实体。

@Entity(tableName = "event")
public class Event {
    @PrimaryKey(autoGenerate = true)
    public int id;

    public String title;
}
Run Code Online (Sandbox Code Playgroud)

这是事件实体的 DAO。

@Dao
public interface EventDao {
    @Query("SELECT * FROM event WHERE event.title LIKE :searchTerm")
    DataSource.Factory<Integer, Event> getFilteredEvent(String searchTerm);
}
Run Code Online (Sandbox Code Playgroud)

这是ViewModel扩展了AndroidViewModel ,它允许通过提供所有事件或根据搜索文本过滤的事件的LiveData< PagedList< Event>>来读取和搜索。我真的很挣扎,每次当filterEvent发生变化时,我都会创建新的LiveData,这可能是多余的或不好的。

private MutableLiveData<Event> filterEvent = new MutableLiveData<>();
private LiveData<PagedList<Event>> data;

private MeDB meDB;

public EventViewModel(Application application) {
    super(application);
    meDB = MeDB.getInstance(application);

    data = Transformations.switchMap(filterEvent, new Function<Event, LiveData<PagedList<Event>>>() {
        @Override
        public LiveData<PagedList<Event>> apply(Event event) {
            if (event == null) {
                // get all the events
                return new LivePagedListBuilder<>(meDB.getEventDao().getAllEvent(), 5).build();
            } else {
                // get events that match the title
                return new LivePagedListBuilder<>(meDB.getEventDao()
                          .getFilteredEvent("%" + event.title + "%"), 5).build();
            }
        }
    });
}

public LiveData<PagedList<Event>> getEvent(Event event) {
    filterEvent.setValue(event);
    return data;
}
Run Code Online (Sandbox Code Playgroud)

对于搜索事件,我使用SearchView。在 onQueryTextChange 中,我编写了以下代码来搜索或在未提供搜索词时显示所有事件,这意味着搜索已完成或取消。

Event dumpEvent;

@Override
public boolean onQueryTextChange(String newText) {

    if (newText.equals("") || newText.length() == 0) {
        // show all the events
        viewModel.getEvent(null).observe(this, events -> adapter.submitList(events));
    }

    // don't create more than one object of event; reuse it every time this methods gets called
    if (dumpEvent == null) {
        dumpEvent = new Event(newText, "", -1, -1);
    }

    dumpEvent.title = newText;

    // get event that match search terms
    viewModel.getEvent(dumpEvent).observe(this, events -> adapter.submitList(events));

    return true;
}
Run Code Online (Sandbox Code Playgroud)

Mir*_*iny 5

感谢George Machibya的精彩回答。但我更喜欢对它做一些修改,如下所示:

  1. 在内存中保留未过滤的数据以使其更快或每次加载它们以优化内存之间存在权衡。我更喜欢将它们保留在内存中,因此我将部分代码更改为如下所示:
listAllFood = Transformations.switchMap(filterFoodName), input -> {
            if (input == null || input.equals("") || input.equals("%%")) {
                //check if the current value is empty load all data else search
                synchronized (this) {
                    //check data is loaded before or not
                    if (listAllFoodsInDb == null)
                        listAllFoodsInDb = new LivePagedListBuilder<>(
                                foodDao.loadAllFood(), config)
                                .build();
                }
                return listAllFoodsInDb;
            } else {
                return new LivePagedListBuilder<>(
                        foodDao.loadAllFoodFromSearch("%" + input + "%"), config)
                        .build();
            }
        });
Run Code Online (Sandbox Code Playgroud)
  1. 使用 debouncer 有助于减少对数据库的查询次数并提高性能。所以我开发了如下DebouncedLiveData类,并从filterFoodName.
public class DebouncedLiveData<T> extends MediatorLiveData<T> {

    private LiveData<T> mSource;
    private int mDuration;
    private Runnable debounceRunnable = new Runnable() {
        @Override
        public void run() {
            DebouncedLiveData.this.postValue(mSource.getValue());
        }
    };
    private Handler handler = new Handler();

    public DebouncedLiveData(LiveData<T> source, int duration) {
        this.mSource = source;
        this.mDuration = duration;

        this.addSource(mSource, new Observer<T>() {
            @Override
            public void onChanged(T t) {
                handler.removeCallbacks(debounceRunnable);
                handler.postDelayed(debounceRunnable, mDuration);
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

然后像下面这样使用它:

listAllFood = Transformations.switchMap(new DebouncedLiveData<>(filterFoodName, 400), input -> {
...
});
Run Code Online (Sandbox Code Playgroud)
  1. 我通常更喜欢在android中使用DataBiding。通过使用两种方式数据绑定,您不再需要使用TextWatcher,您可以直接将 TextView 绑定到 viewModel。

顺便说一句,我修改了 George Machibya 解决方案并将其推送到我的 Github 中。有关更多详细信息,您可以在此处查看