Last active
August 29, 2015 14:23
-
-
Save pakoito/5f4584c0ccad322080d1 to your computer and use it in GitHub Desktop.
Simple RecyclerView.OnScrollListener with RxJava subjects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.