gpt4 book ai didi

android-viewmodel - 从 Room 观察 LiveData 会导致 PagedListAdapter 刷新,ViewModel 也会在方向更改时刷新数据

转载 作者:行者123 更新时间:2023-12-04 09:00:54 24 4
gpt4 key购买 nike

我正在构建一个应用程序,该应用程序使用 ArticleBoundaryCallback 来初始化对 API 的调用,并将响应存储在 Room 中。我也在使用 LiveData 收听该表,并在 PagedListAdapter 中显示项目。

问题是每次在 Room 的(文章)表中插入新数据时,整个列表都会刷新。

此外,在配置更改时,似乎再次获取了整个数据(ViewModel 不保留它,RecyclerView 被重新创建)。

在每次插入时, RecyclerView 都会跳转(如果插入的是新数据,则跳转几行,或者如果它用旧数据替换新数据,则在开头)。

整个代码在这个 GitHub repo .

我的类(class)是:

文章:

@Entity(tableName = "article",
indices={@Index(value="id")})public class Article {
@PrimaryKey(autoGenerate = false)
@SerializedName("_id")
@Expose
@NonNull
private String id;
@SerializedName("web_url")
@Expose
private String webUrl;
@SerializedName("snippet")
@Expose
private String snippet;
@SerializedName("print_page")
@Expose
private String printPage;
@SerializedName("source")
@Expose
private String source;
@SerializedName("multimedia")
@Expose
@Ignore
private List<Multimedium> multimedia = null;

文章 DAO:
@Dao
public interface ArticleDao {

@Insert(onConflict = OnConflictStrategy.REPLACE)
long insert(Article article);

@Insert(onConflict = OnConflictStrategy.REPLACE)
void update(Article... repos);

@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertArticles(List<Article> articles);


@Delete
void delete(Article... articles);

@Query("DELETE FROM article")
void deleteAll();

@Query("SELECT * FROM article")
List<Article> getArticles();

@Query("SELECT * FROM article")
DataSource.Factory<Integer, Article> getAllArticles();}

LocalCache(从 Room 存储/检索)
public class LocalCache {
private static final String TAG = LocalCache.class.getSimpleName();
private ArticleDao articleDao;
private Executor ioExecutor;

public LocalCache(AppDatabase appDatabase, Executor ioExecutor) {
this.articleDao = appDatabase.getArticleDao();
this.ioExecutor = ioExecutor;
}

public void insertAllArticles(List<Article> articleArrayList){
ioExecutor.execute(new Runnable() {
@Override
public void run() {
Log.d(TAG, "inserting " + articleArrayList.size() + " repos");
articleDao.insertArticles(articleArrayList);
}
});
}

public void otherFunction(ArrayList<Article> articleArrayList){
// TODO
}

public DataSource.Factory<Integer, Article> getAllArticles() {
return articleDao.getAllArticles();
}

AppRepository
public class AppRepository {

private static final String TAG = AppRepository.class.getSimpleName();
private static final int DATABASE_PAGE_SIZE = 20;
private Service service;
private LocalCache localCache;
private LiveData<PagedList<Article>> mPagedListLiveData;

public AppRepository(Service service, LocalCache localCache) {
this.service = service;
this.localCache = localCache;
}

/**
* Search - match the query.
*/
public ApiSearchResultObject search(String q){
Log.d(TAG, "New query: " + q);

// Get data source factory from the local cache
DataSource.Factory dataSourceFactory = localCache.getAllArticles();

// every new query creates a new BoundaryCallback
// The BoundaryCallback will observe when the user reaches to the edges of
// the list and update the database with extra data
ArticleBoundaryCallback boundaryCallback = new ArticleBoundaryCallback(q, service, localCache);

// Get the paged list
LiveData data = new LivePagedListBuilder(dataSourceFactory, DATABASE_PAGE_SIZE)
.setBoundaryCallback(boundaryCallback)
.build();

mPagedListLiveData = data;

ApiSearchResultObject apiSearchResultObject = new ApiSearchResultObject();
apiSearchResultObject.setArticles(data);

return apiSearchResultObject;
}

public DataSource.Factory getAllArticles() {
return localCache.getAllArticles();
}

public void insertAllArticles(ArrayList<Article> articleList) {
localCache.insertAllArticles(articleList);
}
}

View 模型
public class DBArticleListViewModel extends ViewModel {

private AppRepository repository;

// init a mutable live data to listen for queries
private MutableLiveData<String> queryLiveData = new MutableLiveData();

// make the search after each new search item is posted with (searchRepo) using "map"
private LiveData<ApiSearchResultObject> repositoryResult = Transformations.map(queryLiveData, queryString -> {
return repository.search(queryString);
});

// constructor, init repo
public DBArticleListViewModel(@NonNull AppRepository repository) {
this.repository = repository;
}

// get my Articles!!
public LiveData<PagedList<Article>> articlesLiveData = Transformations.switchMap(repositoryResult, object ->
object.getArticles());

// get teh Network errors!
public LiveData<String> errorsLiveData = Transformations.switchMap(repositoryResult, object ->
object.getNetworkErrors());


// Search REPO
public final void searchRepo(@NonNull String queryString) {
this.queryLiveData.postValue(queryString);
}

// LAST Query string used
public final String lastQueryValue() {
return (String)this.queryLiveData.getValue();
}

事件 - 从 VM 观察
 DummyPagedListAdapter articleListAdapter = new DummyPagedListAdapter(this);

localDBViewModel = ViewModelProviders.of(this, Injection.provideViewModelFactory(this)).get(DBArticleListViewModel.class);

localDBViewModel.articlesLiveData.observe(this, pagedListLiveData ->{
Log.d(TAG, "articlesLiveData.observe size: " + pagedListLiveData.size());
if(pagedListLiveData != null)
articleListAdapter.submitList(pagedListLiveData);
});

recyclerView.setAdapter(articleListAdapter);

适配器
public class DummyPagedListAdapter extends PagedListAdapter<Article, ArticleViewHolder> {

private final ArticleListActivity mParentActivity;

public DummyPagedListAdapter(ArticleListActivity parentActivity) {
super(Article.DIFF_CALLBACK);
mParentActivity = parentActivity;
}

@NonNull
@Override
public ArticleViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(mParentActivity).inflate(R.layout.article_list_content, parent, false);
return new ArticleViewHolder(itemView);
}

@Override
public void onBindViewHolder(@NonNull ArticleViewHolder holder, int position) {
Article article = getItem(position);

if (article != null) {
holder.bindTo(article);
} else {
holder.clear();
}
}
}

差价
   public static DiffUtil.ItemCallback<Article> DIFF_CALLBACK = new 
DiffUtil.ItemCallback<Article>() {
@Override
public boolean areItemsTheSame(@NonNull Article oldItem, @NonNull
Article newItem) {
return oldItem.getId() == newItem.getId();
}

@Override
public boolean areContentsTheSame(@NonNull Article oldItem, @NonNull
Article newItem) {
return oldItem.getWebUrl() == newItem.getWebUrl();
}
};

我真的需要解决这个问题。谢谢!

最佳答案

是的..花了我一段时间但我解决了它。正如我所想的,愚蠢的问题:在适配器用来决定从观察到的数据集中添加什么和忽略什么的 DIFF_CALLBACK 中,我使用作为比较器 oldItem.getId() == newItem.getId() 这是字符串! !!当然,适配器总是获得“新值”并添加它们。

更正 DiffUtil.ItemCallback

 public static DiffUtil.ItemCallback<Article> DIFF_CALLBACK = new DiffUtil.ItemCallback<Article>() {
@Override
public boolean areItemsTheSame(@NonNull Article oldItem, @NonNull Article newItem) {
return oldItem.getStoreOrder() == newItem.getStoreOrder();
}

@Override
public boolean areContentsTheSame(@NonNull Article oldItem, @NonNull Article newItem) {
return oldItem.getId().equals(newItem.getId()) && oldItem.getWebUrl().equals(newItem.getWebUrl());
}
};

我希望这将是一个提醒,始终关注最基本的事情。我为此浪费了很多时间。希望你不会:)

关于android-viewmodel - 从 Room 观察 LiveData 会导致 PagedListAdapter 刷新,ViewModel 也会在方向更改时刷新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51455071/

24 4 0