【发布时间】: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();
}
【问题讨论】: