androidfragmentrx-java2debouncingpublishsubject

Debounce makes PublishSubject emit only one item


protected PublishSubject<Integer> onScrollS = PublishSubject.create();

public void onActivityCreated(...) {

        ...

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NotNull RecyclerView recyclerView, int dx, int dy) {
                if (dy == 0) return;
                Log.i("Rx", "onNext(" + dy + ")");
                onScrollS.onNext(dy);
            }
        });
        disposable = onScrollS
                .debounce(200, TimeUnit.MILLISECONDS) // <-- this breaks everything
                .subscribe(this);
    }

    // the Fragment implements Consumer interface
    @Override
    public void accept(Integer integer) throws Exception {
        Log.i("Rx", "Accept: " + integer);
        recyclerViewOnScrolled();
    }

When I add .debounce call to my onScrollS subject the accept method is called only once.

I can scroll and scroll then pause for ten seconds and nothing happens.

Anybody knows why ?

I tried something like this:

.debounce((Function<Integer, Observable<Integer>>) value - > {
    return Observable.just(value).delay(1, TimeUnit.SECONDS);
})

And it works if I remove the delay part.


Solution

  • here may be a few problems:

        onScrollS
                    .debounce(200, TimeUnit.MILLISECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Integer>() {
                        @Override
                        public void accept(Integer dy) throws Exception {
                            // TODO handle scroll event
                        }
                    });