【问题标题】:DataSource.Factory is not using correct variable value Android PagingDataSource.Factory 未使用正确的变量值 Android Paging
【发布时间】:2021-02-15 06:32:55
【问题描述】:

我有一个 DataSource.Factory 类“CategoriesDataSourceFactory”。我正在将一个字符串变量“关键字”传递给类。该类的 create 方法是使用该关键字创建一个 DataSource 对象。问题是当 CategoriesDataSourceFactory 第一次用关键字的一些值初始化时。无论使用不同的关键字值创建 CategoriesDataSourceFactory 的新实例多少次,该值都不会改变。

public class CategoriesDataSourceFactory extends DataSource.Factory<Long, CategoryModel> {
private CategoriesDataSource categoriesDataSource;
private MutableLiveData<CategoriesDataSource> categoriesDataSourceMutableLiveData;
String keyWord;
public CategoriesDataSourceFactory(String keyWord) {
    this.keyWord =keyWord;
    this.categoriesDataSourceMutableLiveData = new MutableLiveData<>();
}

@NonNull
@Override
public DataSource<Long, CategoryModel> create() {
    Log.i("KeyWord",keyWord!=null?keyWord:"Keyword Null"); //it is showing value of first time the object of this class is initilized.

    categoriesDataSource = new CategoriesDataSource(keyWord);
    categoriesDataSourceMutableLiveData.postValue(categoriesDataSource);
    return categoriesDataSource;
}

我正在从视图模型中初始化它

  public class CategoriesFragmentViewModel extends ViewModel {
    // TODO: Implement the ViewModel

    LiveData<PagedList<CategoryModel>> categoryListLiveData;
    CategoriesDataSourceFactory categoriesDataSourceFactory;
    public CategoriesFragmentViewModel() {

       init("first time");
    }

// I am calling this method multiple times with  different keyword value 
    public void init(String keyWord) {
        Log.i("KeyWordViewmodel",keyWord!=null?keyWord:"Keyword Null");
        categoriesDataSourceFactory = new CategoriesDataSourceFactory(keyWord);

        PagedList.Config config = new PagedList.Config.Builder()
                .setEnablePlaceholders(true)
                .setInitialLoadSizeHint(10)
                .setPageSize(10)
                .setPrefetchDistance(4)
                .build();

        categoryListLiveData = new LivePagedListBuilder<Long,CategoryModel>(categoriesDataSourceFactory,config).build();
    }

【问题讨论】:

    标签: android android-paging


    【解决方案1】:

    看起来你实际上是在构建一个全新的LiveData,而不是将新的PagedList 发布到categoryListLiveData 以便现有观察者可以在keyWord 更改时接收新值。

    考虑在 LiveData&lt;String&gt; 的搜索词上使用 Transformations.switchMap,然后映射到 LiveData&lt;PagedList&gt;,这样您就不会让观察者掉到地板上并可能错过泄漏。

    Transformations.switchMap(keyWordLiveData, keyWord -> {
      ...
      LivePagedListBuilder<..>(...).build()
    });
    

    【讨论】:

    • 你能用更新后的代码更新你的代码示例吗? categoryListLiveData = new LivePagedListBuilder&lt;Long,CategoryModel&gt;(categoriesDataSourceFactory,config).build(); 这一行完全替换了您的 LiveData 实例,而不是发出一个新值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    相关资源
    最近更新 更多