我正在使用具有GridLayoutManager的RecyclerView。对于网格中的每个项目,我需要调用REST API来检索数据。然后,在从远程异步获取数据之后,我使用UIL来加载/显示图像。
一切似乎都很好。但是我发现对于特定的项目,onBindViewHolder被调用太多太多太多次。
以下是代码示例: 言而无信,让我向您展示代码:
一切似乎都很好。但是我发现对于特定的项目,onBindViewHolder被调用太多太多太多次。
以下是代码示例: 言而无信,让我向您展示代码:
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
EditCourseImageAttachmentHolder holder = (EditCourseImageAttachmentHolder) viewHolder;
holder.itemView.setLayoutParams(getLayoutParams(position));
holder.attachmentView.initData(dataSource.get(headerView == null ? position : position - 1), urlMap);
}
public static class EditCourseImageAttachmentHolder extends RecyclerView.ViewHolder {
public final AttachmentView attachmentView;
public EditCourseImageAttachmentHolder(AttachmentView itemView) {
super(itemView);
this.attachmentView = itemView;
}
}
-----------AttachmentView.Java-----------------
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
subscription = tryLoadLocalImage(data)
.subscribeOn(Schedulers.io())
.flatMap(new Func1<String, Observable<String>>() {
@Override
public Observable<String> call(String localImageUrl) {
if (StringUtils.isNotBlank(localImageUrl)) {
return Observable.just(localImageUrl);
}
if (urlMap.containsKey(data.getUid())) {
return Observable.just(urlMap.get(data.getUid()));
} else {
//Remote API call
String qiNiuUrl = getQiNiuUrl(data);
urlMap.put(data.getUid(), qiNiuUrl);
return Observable.just(qiNiuUrl);
}
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<String>() {
@Override
public void call(String localImageUrl) {
showImage(localImageUrl);
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
}
});
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (subscription != null && subscription.isUnsubscribed()) {
subscription.unsubscribe();
}
}