Skip to content

Instantly share code, notes, and snippets.

@pakoito
Last active August 29, 2015 14:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pakoito/5f4584c0ccad322080d1 to your computer and use it in GitHub Desktop.
Save pakoito/5f4584c0ccad322080d1 to your computer and use it in GitHub Desktop.
Simple RecyclerView.OnScrollListener with RxJava subjects
Apache License, Version 2.0
===========================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.n writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
public class RecyclerSimpleScrollListener extends RecyclerView.OnScrollListener {
private final SerializedSubject<Direction, Direction> scrollBus;
public RecyclerSimpleScrollListener() {
scrollBus = new SerializedSubject<>(PublishSubject.<Direction> create());
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (0 < dy) {
scrollBus.onNext(Direction.DOWN);
} else if (0 > dy) {
scrollBus.onNext(Direction.UP);
} else if (0 == dy) {
scrollBus.onNext(Direction.NEUTRAL);
}
}
public Observable<Direction> getDirectionObservable() {
return scrollBus.onBackpressureDrop().distinctUntilChanged().asObservable();
}
public enum Direction {
UP, DOWN, NEUTRAL
}
}
@mhdatie
Copy link

mhdatie commented Jun 25, 2015

Neat. I am only using Rx with network calls. I'm not sure if I should handle the UI with Subjects or just deal with normal listeners. I really like how you are handling the touch events in getDirectionObservables(). Less code as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment