android - 在 Repository 类中观察 Forever 是一个好习惯吗? db+network 分页列表

标签 android android-livedata android-architecture-components android-mvvm android-paging

我正在按照架构指南构建应用程序。实现房间数据库缓存 + 网络。需要从单独的实体获取最新的页码。

我的模型:

@Entity(tableName = "top_rated_movie_page")
public class Top_Rated_Movies_Page {

@PrimaryKey(autoGenerate = true)
private int db_id;
private Integer page;
private Integer total_results;
private Integer total_pages;
@Ignore
private List<Result> results;
...
Result类包含我在分页列表中显示的数据,该列表观察 db 的变化。

使用 PagedList.BoundaryCallback我需要从网络中获取新数据并将其插入数据库。
但我需要以某种方式获取页码。
我的道:
@Insert
void insertAll(Top_Rated_Movies_Page page,List<Result> top_rated_results);

@Query("SELECT * FROM Result")
DataSource.Factory<Integer, Result> getAllResults();

@Query("SELECT * FROM top_rated_movie_page WHERE page= (SELECT MAX(page) FROM top_rated_movie_page)")
LiveData<Top_Rated_Movies_Page> getMoviePage();

我想观察 Top_Rated_Movies_Page来自我的存储库类中的 db,带有 observeForever()获取该页码。
这是解决这个问题的最好方法吗?

最佳答案

因为您读取下一页键或更新后备数据库的唯一时间是通过BoundaryCallback。 ,你可以直接读/写你的下一页键。

所以在你的onItemAtEndLoad()实现你想要的东西:

String nextMoviePage = db.runInTransaction(() -> {
    movieDao.nextRemoteKey().key;
});

// Make sure not to run on main thread
MovieNetworkResponse response = networkApi.fetchNextMoviePage(remoteKey);

db.runInTransaction(() -> {
    movieDao.clearAll(); // Remove previous key
    movieDao.insertKey(RemoteKey(response.nextPageKey)); // Insert new key
    movieDao.insertAll(response.movies); // Update DataSource + invalidate()
});

你的 DAO:
@Insert
void insertAll(List<Result> top_rated_results);

@Query("SELECT * FROM Result")
DataSource.Factory<Integer, Result> getAllResults();

@Query("SELECT * FROM result_key LIMIT 1")
String nextRemoteKey();

@Insert
void insertKey(RemoteKey remoteKey);

并且不要忘记在您希望刷新数据时清除项目和 remoteKey!

如果您想跟踪不同的查询键,您只需将该列添加到您的 RemoteKey 实体。

仅供引用:Paging2 已被 Paging3 取代(尽管刚刚推出 alpha01),这里是类似的 Paging3 示例,它完全解决了您的用例:https://github.com/android/architecture-components-samples/blob/master/PagingWithNetworkSample/app/src/main/java/com/android/example/paging/pagingwithnetwork/reddit/repository/inDb/PageKeyedRemoteMediator.kt

关于android - 在 Repository 类中观察 Forever 是一个好习惯吗? db+network 分页列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62321170/

相关文章:

Android OrmLite 预填充数据库

android - 可变实时数据值在创建 fragment 时更新

generics - 对 Kotlin 何时推断平台类型感到困惑

android - Room - LiveData 观察者在数据库更新时不会触发

android - 我很少发生无法从 onDestroy 访问 ViewModel

android - 如何制作一个刷新抽屉中 fragment 的Android刷新按钮?

android - 相对布局中心的进度条

android - 为什么 GestureOverlayView 这么慢?

android - 具有 mutablelivedata 支持属性的观察 livedata 如何知道在从未直接更新时触发观察者?

android - 无法创建自定义 ViewModel 的实例