ReactiveX / RxAndroid

RxJava bindings for Android
Apache License 2.0
19.89k stars 2.94k forks source link

Add ViewObservable.touches() for View.OnTouchListener #154

Closed passsy closed 9 years ago

passsy commented 9 years ago

There is currently only an implementation to subscribe to click events. I'd like to observe touch events from the View.OnTouchListener.

I already implemented it https://gist.github.com/passsy/96f3e268f53a315ba7df

Sample usecase: show/hide a password depending on the pressed state of a button

ViewObservable.bindView(mPasswordShowBtn, touches(mPasswordShowBtn))
    .map(new Func1<OnTouchEvent, Boolean>() {
        @Override
        public Boolean call(final OnTouchEvent onTouchEvent) {
            return isTouchingEvent(onTouchEvent.event());
        }
    })
    .distinctUntilChanged()
    .subscribe(new Action1<Boolean>() {
        @Override
        public void call(final Boolean touched) {
            mPassword.setTransformationMethod(touched ? null : new PasswordTransformationMethod());
        }
    });
private static boolean isTouchingEvent(final MotionEvent event) {
    final int action = event.getAction() & MotionEvent.ACTION_MASK;
    switch (action) {
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_MOVE:
            return true;
        default:
        case MotionEvent.ACTION_OUTSIDE:
        case MotionEvent.ACTION_CANCEL:
        case MotionEvent.ACTION_UP:
            return false;
    }
}

public static Observable<OnTouchEvent> touches(final View view) {
    return Observable.create(new OnSubscribeViewTouch(view));
}

I try to fit the contributing guidelines once I get feedback if this is something that should be added to RxAndroid.

JakeWharton commented 9 years ago

This is already in https://github.com/JakeWharton/RxBinding but per #172 this won't be going into RxAndroid core.