我在片段中有一个RecyclerView,项目点击是使用RxJava2处理的,如this SO answer中所述,它在非片段中工作正常。
private PublishSubject<Place> itemViewClickSubject = PublishSubject.create();
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.search_result_view, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
// convert click events into reactive stream
RxView.clicks(view)
.takeUntil(RxView.detaches(parent))
// viewHolder.getPlace() is null until it get bound
.map(__ -> viewHolder.getPlace())
.subscribe(itemViewClickSubject);
return viewHolder;
}
片段中的RecyclerView只能运行一次。项目点击片段被另一个片段替换。在按下后,出现RecyclerView片段,但点击不再起作用。
如果我删除.takeUntil(RxView.detaches(parent))
行,它会有效。我认为当它没有显示时,需要打破RxView click与RecyclerView的强绑定(Detached)。我该如何解决这个问题?我希望使用附加/分离事件之一解决问题,任何建议都会很棒!感谢。
答案 0 :(得分:4)
为了回答您的问题和评论,我发送了整个RecylerView + RxJava的解决方案:
private PublishSubject<Place> itemViewClickSubject = PublishSubject.create();
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
RxView.clicks(viewHolder.itemView) //viewHolder.itemView here You have access to view
.map(aVoid -> viewHolder.getPlace())
.subscribe(itemViewClickSubject);
}
@Override
public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
itemViewClickSubject.onComplete(); //here we avoid memory leaks
}