使用Android分页库的嵌套回收器视图
我正在尝试使用android分页库来显示图像提要。每个图像可以包含许多注释,并且可以使用各种参数进行过滤 目前,我正在使用PhotoAdapter内部的ViewModel为PhotoAdapter中的每个项目向CommentAdapter提交一个过滤后的注释列表 尽管我相信在适配器中引用ViewModel容易导致内存泄漏,并破坏ViewModel的用途 片段:使用Android分页库的嵌套回收器视图,android,android-recyclerview,android-architecture-components,android-livedata,android-viewmodel,Android,Android Recyclerview,Android Architecture Components,Android Livedata,Android Viewmodel,我正在尝试使用android分页库来显示图像提要。每个图像可以包含许多注释,并且可以使用各种参数进行过滤 目前,我正在使用PhotoAdapter内部的ViewModel为PhotoAdapter中的每个项目向CommentAdapter提交一个过滤后的注释列表 尽管我相信在适配器中引用ViewModel容易导致内存泄漏,并破坏ViewModel的用途 片段: photosViewModel.getPhotosLiveData().data().observe(getViewLifecycleO
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);
});
});
}
}
}
公共类PhotoAdapter扩展了PagedListAdapter{
语境;
MyViewModel MyViewModel;//在适配器中存储视图模型是个坏主意
CommentsViewModel CommentsViewModel;
……样板代码。。。。。
@凌驾
public void onBindViewHolder(@NonNull PhotoViewHolder,int位置){
字符串photoId=getItem(位置);
支架。设置适配器(photoId);
}
公共类PhotoViewHolder扩展了RecyclerView.ViewHolder{
私人RecyclerView评论RecyclerView;
私有CommentRecyclerAdapter commentAdapter;
专用void设置适配器(字符串photoId){
myViewModel.getMe().observe(上下文,me->{
FilterQuery FilterQuery=新的FilterQuery(photoId,me.getLocation(),me.getPreferences());
CommentsSearchResult=commentsViewModel.GetCommentsViewData(filterQuery);
结果.注释.观察(上下文,(页面列表项)->{
commentAdapter.提交列表(项目);
});
});
}
}
}
这种方法“有效”,但实现这种模式的正确方法是什么?这种模式不容易泄漏,并且正确地利用了ViewModels?您找到解决方案了吗?我正在尝试实现相同的。。。