将视图模型传递到 recyclerview 适配器会导致内存泄漏吗?

Will a passed viewmodel into a recyclerview adapter cause for memory leaks?

目前我正在试验视图模型,想知道将视图模型传递给 recyclerview 适配器是否会导致内存泄漏?适配器中视图模型的唯一目的是提供新的 url 图像以显示在 activity

我不知道界面是更好的方法还是有更好的方法从 recyclerview 接收 onclick 事件?

这是我的代码:

视图模型:

public class WallDetailViewModel extends AndroidViewModel {
private final String apiAddress = "*";
private BlindWall detailWall;
private MutableLiveData<String> mainImageUrl;

public WallDetailViewModel(@NonNull Application application) {
    super(application);
}

public LiveData<String> getMainImageUrl() {
    if(mainImageUrl == null) {
        mainImageUrl = new MutableLiveData<>();
        mainImageUrl.postValue(getImageUrl(0));
    }
    return mainImageUrl;
}

public void setWall(BlindWall wall) {
    detailWall = wall;
}

public String getImageUrl(int position) {
    String returnValue = null;
    if(position >= 0 && position < detailWall.getImagesUrls().size()) {
        returnValue = apiAddress + detailWall.getImagesUrls().get(position);
    }
    return returnValue;
}

public String getWallName() {
    return detailWall.getTitle();
}

public String getDutchDescription() {
    return detailWall.getDescriptionDutch();
}

public String getEnglishDescription() {
    return detailWall.getDescriptionEnglish();
}

public int getImageUrlSize() {
    return detailWall.getImagesUrls().size();
}

public void setMainImage(String url) {
    mainImageUrl.postValue(url);
}

}

适配器:

public class ImageSliderAdapter extends RecyclerView.Adapter<ImageSliderAdapter.ViewHolder2> {
private WallDetailViewModel viewModel;

public ImageSliderAdapter(WallDetailViewModel viewModel) {
    this.viewModel = viewModel;
}

public static class ViewHolder2 extends RecyclerView.ViewHolder {
    public ImageView WallFrontPaper;

    public ViewHolder2(View itemView) {
        super(itemView);
        WallFrontPaper = itemView.findViewById(R.id.ImageItem);
    }
}

@Override
public ViewHolder2 onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View v = inflater.inflate(R.layout.imageslider_item, parent, false);

    return new ViewHolder2(v);
}

@Override
public void onBindViewHolder(ViewHolder2 holder, int position) {
    Picasso.with(holder.itemView.getContext()).load(viewModel.getImageUrl(position)).fit().centerCrop().into(holder.WallFrontPaper);
    holder.WallFrontPaper.setOnClickListener(view -> viewModel.setMainImage(viewModel.getImageUrl(position)));
}

@Override
public int getItemCount() {
    return viewModel.getImageUrlSize();
}

}

谢谢,

伊恩

根据您发布的代码,我认为您应该没问题。但是,正如您提到的那样,拥有一个接口可以帮助使事情变得更清晰,因为您可以将它传递给您的适配器,而不会暴露整个视图模型。

看着这个 .setOnClickListener(view -> viewModel.setMainImage(viewModel.getImageUrl(position))); 让我想知道你是否不能让视图模型知道某个项目已被单击,因为你再次使用视图模型来确定要传递哪个图像 url参数,基于位置。

因此,如果使用界面,您会得到类似 setOnClickListener(view -> itemClickListener.itemClicked(position) 的东西。您的视图模型将实现此接口。