RxJava2去抖功能在RecyclerView中无法正常工作

我正在尝试创建一个Custom ImageButton,当用户停止点击该按钮1秒钟时,它将累积点击并触发一个事件。

我使用了debounce函数来完成此操作。

自定义ImageButton:

public class MBImageButton extends ImageButton {

    private AtomicInteger mCounter;
    private Disposable mDisposable;
    private Observable<Object> observable;
    private OnAccumulatedRequestsRead mOnAccumulatedRequestsRead;
    private OnEverClickListener mOnEverClickListener;
    private int emitEveryMilli = 1000; // every 1 second by default
    private boolean shouldDisposeOnDetachFromWindow = true;

    public MBImageButton(Context context) {
        super(context);
        init();
    }

    public MBImageButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MBImageButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public void setAccumulatedClickListeners(OnEverClickListener onEverClickListener,
                                             OnAccumulatedRequestsRead onAccumulatedRequestsRead) {
        setOnAccumulatedRequestsRead(onAccumulatedRequestsRead);
        setOnEverClickListener(onEverClickListener);
        initClickObservable();
        subscribe();
    }

    private void initClickObservable() {
        observable = Observable.create(emitter -> {
            emitter.setCancellable(() -> setOnClickListener(null));
            try {
                setOnClickListener(view -> {
                    try {
                        final int currentCount = mCounter.incrementAndGet();
                        Timber.d("Clicked: " + currentCount);
                        if (mOnEverClickListener != null) {
                            mOnEverClickListener.onEveryClickListener(currentCount);
                        }
                        emitter.onNext(new Object());
                    } catch (Exception e) {
                        emitter.onError(e);
                    }
                });
            } catch (Exception e) {
                emitter.onError(e);
            }
        }).doOnSubscribe(disposable -> mDisposable = disposable)
                               .debounce(emitEveryMilli, TimeUnit.MILLISECONDS);
    }

    private void subscribe() {
        observable.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(o -> {
                    try {
                        final int count = mCounter.get();
                        if(count==0) return;
                        mCounter.set(0);
                        Timber.d("Accumulated Clicks: " + count);
                        if (mOnAccumulatedRequestsRead != null) {
                            mOnAccumulatedRequestsRead.onAccumulatedRequestsReady(count);
                        }
                    } catch (Exception e) {
                        Timber.e(e);
                    }
                }, Timber::e);
    }

    private void init() {
        mCounter = new AtomicInteger(0);
    }

    public void disposeAccumulatedClickListeners() {
        if (mDisposable != null) {
            mDisposable.dispose();
        }
    }

    public void shouldDisposeOnDetachFromWindow(boolean shouldDisposeOnDetachFromWindow) {
        this.shouldDisposeOnDetachFromWindow = shouldDisposeOnDetachFromWindow;
    }

    public void setEmitEveryMilliseconds(int emitEveryMilli) {
        this.emitEveryMilli = emitEveryMilli;
        initClickObservable();
        subscribe();
    }

    private void setOnEverClickListener(OnEverClickListener onEverClickListener) {
        mOnEverClickListener = onEverClickListener;
    }

    private void setOnAccumulatedRequestsRead(OnAccumulatedRequestsRead onAccumulatedRequestsRead) {
        mOnAccumulatedRequestsRead = onAccumulatedRequestsRead;
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (shouldDisposeOnDetachFromWindow) {
            if (mDisposable != null) {
                mDisposable.dispose();
            }
        }
    }

    public interface OnAccumulatedRequestsRead {
        void onAccumulatedRequestsReady(int count);
    }

    public interface OnEverClickListener {
        void onEveryClickListener(int currentCount);
    }
}

设置这个imageButton进行反弹的功能是:

setAccumulatedClickListeners(OnEverClickListener, OnAccumulatedRequestsRead)

当我从RecyclerView设置这个视图时,一切正常,

当我按顺序点击9次时,结果如下所示:

D/MBImageButton: Clicked: 1
D/MBImageButton: Clicked: 2
D/MBImageButton: Clicked: 3
D/MBImageButton: Clicked: 4
D/MBImageButton: Clicked: 5
D/MBImageButton: Clicked: 6
D/MBImageButton: Clicked: 7
D/MBImageButton: Clicked: 8
D/MBImageButton: Clicked: 9
D/MBImageButton: Accumulated Clicks: 9

当我将此自定义ImageButton添加到RecyclerView ViewHolder时,结果对于相同的点击次数不正确:

D/MBImageButton: Clicked: 1
D/MBImageButton: Clicked: 2
D/MBImageButton: Clicked: 1
D/MBImageButton: Clicked: 3
D/MBImageButton: Clicked: 2
D/MBImageButton: Clicked: 4
D/MBImageButton: Accumulated Clicks: 4
D/MBImageButton: Clicked: 1
D/MBImageButton: Accumulated Clicks: 2
D/MBImageButton: Clicked: 2
D/MBImageButton: Accumulated Clicks: 2
D/MBImageButton: Accumulated Clicks: 0
D/MBImageButton: Clicked: 1
D/MBImageButton: Accumulated Clicks: 1
D/MBImageButton: Accumulated Clicks: 0
D/MBImageButton: Accumulated Clicks: 0

这又是9次连续点击的结果:

D/MBImageButton: Clicked: 1
D/MBImageButton: Clicked: 2
D/MBImageButton: Clicked: 1
D/MBImageButton: Clicked: 3
D/MBImageButton: Clicked: 2
D/MBImageButton: Clicked: 4
D/MBImageButton: Clicked: 3
D/MBImageButton: Accumulated Clicks: 4
D/MBImageButton: Clicked: 1
D/MBImageButton: Accumulated Clicks: 3
D/MBImageButton: Accumulated Clicks: 1
D/MBImageButton: Accumulated Clicks: 0
D/MBImageButton: Clicked: 1
D/MBImageButton: Accumulated Clicks: 1
D/MBImageButton: Accumulated Clicks: 0
D/MBImageButton: Accumulated Clicks: 0
D/MBImageButton: Accumulated Clicks: 0

在这两个时间我点击了相同的间隔时间,但是当这个按钮添加到RecyclerView它给出了奇怪的结果。

可能是什么问题?

更新:

我的适配器简化实施:

public class ProductRVAdapter extends BaseProductRVAdapter<ProductRVAdapter.ProductVH> {

    private ProductAdapterListener mProductAdapterListener;

    public ProductRVAdapter(List<Product> productList, ProductAdapterListener productAdapterListener) {
        super(productList);
        mProductAdapterListener = productAdapterListener;
    }

    @Override
    public ProductVH onCreateViewHolder(ViewGroup parent, int viewType) {
        final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_product, parent, false);
        return new ProductVH(view);
    }

    @Override
    public void onBindViewHolder(ProductVH holder, int position) {
        holder.bind(productList.get(position), position);

        holder.ib_decrease.setAccumulatedClickListeners(currentCount -> onProductAdapterDecreaseClicked.onClick(holder.ib_decrease),
                count -> {
                    if (mProductAdapterListener != null) {
                        mProductAdapterListener.onProductAdapterProductChangeToWSListener(productList.get(position), position, -count);
                    }
                });

        holder.ib_add.setAccumulatedClickListeners(currentCount -> onProductAdapterAddToCartClicked.onClick(holder.ib_add),
                count -> {
                    if (mProductAdapterListener != null) {
                        mProductAdapterListener.onProductAdapterProductChangeToWSListener(productList.get(position), position, count);
                    }
                });
    }

    public interface ProductAdapterListener {

        void onProductAdapterAddToCartClicked(Product product, int position);

        void onProductAdapterProductChangeToWSListener(Product product, int position, int amountChanged);

        void onProductAdapterDecreaseClicked(Product product, int position);
    }

    public static class ProductVH extends RecyclerView.ViewHolder {
        @BindView(R.id.iv_productImage)
        ImageView iv_producImage;
        @BindView(R.id.tv_productName)
        TextView tv_productName;
        @BindView(R.id.tv_prodAmount)
        MBTextView tv_prodAmount;

        @BindView(R.id.ib_decrease)
        MBImageButton ib_decrease;
        @BindView(R.id.ib_add)
        MBImageButton ib_add;

        ProductVH(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }


        public void bind(Product product, int position) {
            tv_productName.setText(product.getName());
            tv_prodAmount.setText(product.getAmount());

            ImageLoader.loadImage(iv_producImage.getContext(), iv_producImage, product.getImg(), R.drawable.ic_category_item);

            ib_decrease.setTag(position);
            ib_add.setTag(position);
        }
    }
}

我得到了解决方案

主要问题是当我在RecyclerView Adapter滚动时,vies会从窗口中分离出来,并调用函数onDetachedFromWindow ,在那个函数中,我从observable中unsubscribe (dispose)

尝试解决方案:

我添加了attachFunction

@Override
protected void onAttachedToWindow() {
    super.onAttachedToWindow();
    if (shouldDisposeOnDetachFromWindow) {
        if (mDisposable != null) {
            if (mDisposable.isDisposed()) {
                initClickObservable();
                subscribe();
            }
        }
    }
}

2.删除了notifyItemChanged(位置)调用

通常我使用notifyItemChange()进行一些修改后更新视图。 现在我通过setText或类似的函数直接更新视图。

它现在可以正常工作。

链接地址: http://www.djcxy.com/p/95253.html

上一篇: RxJava2 debounce function not working properly in RecyclerView

下一篇: Type quantifiers in Haskell functions