我正在尝试使用android页面库来显示图像供稿。每个图像可以包含许多注释,并可以使用各种参数进行过滤。
当前,我正在使用PhotoAdapter内部的ViewModel来为PhotoAdapter中的每个项目向CommentAdapter提交评论的筛选列表。
尽管我相信在适配器内部引用ViewModel容易导致内存泄漏并破坏ViewModel的用途。
片段中:
photosViewModel.getPhotosLiveData().data().observe(getViewLifecycleOwner(), (photoIds) -> {
photoAdapter.submitList(photoIds);
});
在PhotoAdapter中:
public class PhotoAdapter extends PagedListAdapter<String, PhotoAdapter.PhotoViewHolder> {
Context context;
MyViewModel myViewModel; //Storing View model in adapter is a bad idea
CommentsViewModel commentsViewModel;
.....boilerplate code.....
@Override
public void onBindViewHolder(@NonNull PhotoViewHolder holder, int position) {
String photoId = getItem(position);
holder.setupAdapter(photoId);
}
public class PhotoViewHolder extends RecyclerView.ViewHolder {
private RecyclerView commentRecyclerView;
private CommentRecyclerAdapter commentAdapter;
private void setupAdapter(String photoId){
myViewModel.getMe().observe(context, me ->{
FilterQuery filterQuery = new FilterQuery(photoId, me.getLocation(), me.getPreferences());
CommentsSearchResult result = commentsViewModel.getCommentsLiveData(filterQuery);
result.comments.observe(context, (PagedList<Comment> items) -> {
commentAdapter.submitList(items);
});
});
}
}
}
此方法“有效”,但是实现不易泄漏且正确利用ViewModels的模式的正确方法是什么?