传递给recyclerview适配器的viewmodel会导致内存泄漏吗?

时间:2018-11-06 21:11:33

标签: android mvvm android-recyclerview viewmodel

当前,我正在尝试使用viewmodel,并想知道是否将viewmodel传递给recyclerview适配器会导致内存泄漏?适配器中的viewmodel的唯一目的是提供要在活动中显示的图像的新URL

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

这是我的代码:

Viewmodel:

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();
}

}

谢谢

伊恩

1 个答案:

答案 0 :(得分:0)

从您发布的代码来看,我应该没问题。但是,如前所述,拥有一个接口可以使事情变得更清晰,因为您可以将其传递给适配器,而无需暴露整个视图模型。

看这一点  .setOnClickListener(view -> viewModel.setMainImage(viewModel.getImageUrl(position)));让我想知道您是否不能仅通过让视图模型知道已单击某个项目,因为您将再次使用视图模型来确定基于哪个图像URL作为参数传递,位置。

因此,如果使用接口,您将拥有类似setOnClickListener(view -> itemClickListener.itemClicked(position)的名称。您的视图模型将实现此接口。