【问题标题】:Android ViewModel and Paging 3 LibraryAndroid ViewModel 和 Paging 3 库
【发布时间】:2022-01-07 00:41:14
【问题描述】:

我正在构建一个聊天应用程序,其中每个数据首先进入房间数据库,然后在数据上插入 recyclerview 以使用新数据进行更新。它按预期工作,但现在我需要将我的分页库更新到版本 3。为此,我需要更新这些更改 根据this linkthis

我已经做了所有的改变,但我被困在viewmodel 班级。我没有得到我需要在这门课中做出什么改变才能使它与paging library version 3一起工作

这是我的视图模型

public class Chat_ViewModel extends ViewModel {

    public final LiveData<PagedList<ChatEntity_TableColums>> chatList;


    public Chat_ViewModel() {
        chatList = new LivePagedListBuilder<>(
                RoomDatabase.getInstance(MyApplication.getmContext(),1).chatDAO().getPaginationChat(String.valueOf(UserID())),20).build();
}

    }

在上面的课程中,我知道 PagedListLivePagedListBuilder 已被弃用,但在这里我不确定在更新的库中替换什么以使其完美运行。

我的房间数据库查询

@Query("SELECT * FROM tapChatter WHERE userName = :UserName ORDER BY ID DESC")
    PagingSource<Integer, ChatEntity_TableColums>  getPaginationChat(String UserName);

面临的问题:

1:我如何更新ViewModel 以获得聊天应用程序的最佳性能?我当前的ViewModel 是否适合聊天应用程序?

2:是否可以在 Room Database 数据更新时更新 RecyclerView UI?

【问题讨论】:

    标签: java android mvvm pagination android-room


    【解决方案1】:

    ViewModelRoom Database 的帮助下,我成功地从 Paging 2 迁移到了 Paging 3,并且确实与 paging 2 库相比非常流畅。很难为 java 用户找到很多文档/教程,所以最后我找到了这些链接来成功迁移。 Link 1 Link 2

    这些是我在ViewHolderFragment 中为分页所做的更改

    在 ViewModel 中创建实时数据

      public final LiveData<PagingData<ChatEntity_TableColums>> chatList;
    
    public Chat_ViewModel() {
        Pager<Integer, ChatEntity_TableColums> pager = new Pager(
                // Create new paging config
                new PagingConfig(20, //  Count of items in one page
                        20, //  Number of items to prefetch
                        false, // Enable placeholders for data which is not yet loaded
                        20, // initialLoadSize - Count of items to be loaded initially
                        200),// maxSize - Count of total items to be shown in recyclerview
                () ->                 RoomDatabase.getInstance(MyApplication.getmContext(),1).chatDAO().getPaginationChat(UserID));
        );
    
        CoroutineScope coroutineScope = ViewModelKt.getViewModelScope(this);
        chatList = PagingLiveData.cachedIn(PagingLiveData.getLiveData(pager),coroutineScope);
    
    }
    

    片段

     viewModel = new ViewModelProvider(this).get(Chat_ViewModel.class);
    
            viewModel.chatList.observe(getViewLifecycleOwner(), new Observer<PagingData<ChatEntity_TableColums>>() {
                @Override
                public void onChanged(PagingData<ChatEntity_TableColums> chatEntity_tableColumsPagingData) {
                    adapter.submitData(getLifecycle(),chatEntity_tableColumsPagingData);
                }
            });
    

    【讨论】:

      猜你喜欢
      • 2023-01-18
      • 1970-01-01
      • 2020-12-12
      • 2020-12-15
      • 2021-10-05
      • 1970-01-01
      • 2021-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多