Skip to content

Instantly share code, notes, and snippets.

@henrytao-me
Last active January 25, 2017 02:20
Show Gist options
  • Save henrytao-me/11f58720b55714a8083d2e445b6c98ea to your computer and use it in GitHub Desktop.
Save henrytao-me/11f58720b55714a8083d2e445b6c98ea to your computer and use it in GitHub Desktop.
Deep press observable for customize backspace view
/*
* Copyright 2017 "Henry Tao <hi@henrytao.me>"
*
* 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.
*/
package com.squar.mychat.util;
import android.view.MotionEvent;
import android.view.View;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.subjects.PublishSubject;
/**
* Created by henrytao on 01/24/17.
*/
public class DeepPress implements View.OnTouchListener {
private static final int DELAY = 200;
private static final int INTERVAL = 90;
public static DeepPress on(View view, int interval) {
return new DeepPress(view, interval);
}
public static DeepPress on(View view) {
return on(view, INTERVAL);
}
private final int mInterval;
private final View mView;
private PublishSubject<Boolean> mSubject;
private Subscription mTimerSubscription;
private DeepPress(View view, int interval) {
mView = view;
mInterval = interval;
}
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
onActionDown();
break;
case MotionEvent.ACTION_UP:
onActionUp();
break;
}
return true;
}
public Observable<Boolean> observe() {
mView.setOnTouchListener(this);
mSubject = PublishSubject.create();
return mSubject.doOnUnsubscribe(this::onUnsubscribe);
}
private void onActionDown() {
resetTimer();
mSubject.onNext(true);
mTimerSubscription = Observable.timer(DELAY, TimeUnit.MILLISECONDS)
.flatMap(aLong -> Observable.interval(mInterval, TimeUnit.MILLISECONDS))
.onBackpressureBuffer()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(aLong -> mSubject.onNext(true));
}
private void onActionUp() {
resetTimer();
mSubject.onNext(false);
}
private void onUnsubscribe() {
resetTimer();
mSubject.onCompleted();
mView.setOnTouchListener(null);
}
private void resetTimer() {
if (mTimerSubscription != null && !mTimerSubscription.isUnsubscribed()) {
mTimerSubscription.unsubscribe();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment