使用Rxjava2防止抖動(dòng) and 重復(fù)點(diǎn)擊

最近項(xiàng)目中為了解決按鈕重復(fù)點(diǎn)擊問題后豫,搜索過程中胁勺,發(fā)現(xiàn)Rxjava居然可以實(shí)現(xiàn)這個(gè)功能,但是問題隨之而來怔昨,網(wǎng)上給出的所有Rxjava的解決方案都是基于Rxjava 1.0版本的雀久,而項(xiàng)目工程中使用的Rxjava2。話不多說趁舀,直接上代碼赖捌,各位看官自己看吧。

具體API區(qū)別可以參考之前的文章:http://www.reibang.com/p/d53463e1c3d6

Rxjava1實(shí)現(xiàn)

RxViewHelp.java

package com.hofon.common.util.help;

import android.support.annotation.NonNull;
import android.view.View;

import com.hofon.common.frame.retrofit.subscribers.RxView;

import java.util.List;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * Created by xfkang on 2017/3/29.
 */

public class RxViewHelp {
    public static void clicks(Action1<View> action, @NonNull View... views) {
        for (View view : views) {
            RxView.clicks(view).throttleFirst(500, TimeUnit.MILLISECONDS).subscribe(action);
        }
    }

    public static Observable<Integer> countDown(int time) {
        if (time < 0) time = 0;
        final int countTime = time;
        return Observable.interval(0, 1, TimeUnit.SECONDS)
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Func1<Long, Integer>() {
                    @Override
                    public Integer call(Long increaseTime) {
                        return countTime - increaseTime.intValue();
                    }
                })
                .take(countTime + 1);
    }
}

RxView.java

package com.hofon.common.frame.retrofit.subscribers;

import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.Adapter;
import com.hofon.doctor.adapter.common.base.RecyclerAdapter;
import rx.Observable;
import static com.hofon.common.frame.retrofit.subscribers.Preconditions.checkNotNull;


/**
 * Created by xfkang on 2017/3/29.
 */

public final class RxView {
    /**
     * 監(jiān)聽onclick事件防抖動(dòng)
     *
     * @param view
     * @return
     */
    @CheckResult
    @NonNull
    public static Observable<View> clicks(@NonNull View view) {
        checkNotNull(view, "view == null");
        return Observable.create(new ViewClickOnSubscribe(view));
    }

    @CheckResult
    @NonNull
    public static <T extends Adapter> Observable<AdapterViewItemClickEvent> itemClickEvents(
            @NonNull RecyclerAdapter<?> view) {
        checkNotNull(view, "view == null");
        return Observable.create(new AdapterViewItemClickEventOnSubscribe(view));
    }
}

Preconditions.java

/*
 * 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.hofon.common.frame.retrofit.subscribers;

import android.os.Looper;

public final class Preconditions {
  public static void checkArgument(boolean assertion, String message) {
    if (!assertion) {
      throw new IllegalArgumentException(message);
    }
  }

  public static <T> T checkNotNull(T value, String message) {
    if (value == null) {
      throw new NullPointerException(message);
    }
    return value;
  }

  public static void checkUiThread() {
    if (Looper.getMainLooper() != Looper.myLooper()) {
      throw new IllegalStateException(
          "Must be called from the main thread. Was: " + Thread.currentThread());
    }
  }

  private Preconditions() {
    throw new AssertionError("No instances.");
  }
}

ViewClickOnSubscribe.java

package com.hofon.common.frame.retrofit.subscribers;

import android.view.View;
import rx.Observable;
import rx.Subscriber;
import rx.android.MainThreadSubscription;

import static com.hofon.common.frame.retrofit.subscribers.Preconditions.checkUiThread;

/**
 * onclick事件防抖動(dòng)
 * 返回view
 */
final class ViewClickOnSubscribe implements Observable.OnSubscribe<View> {
  final View view;

  ViewClickOnSubscribe(View view) {
    this.view = view;
  }

  @Override
  public void call(final Subscriber<? super View> subscriber) {
    checkUiThread();

    View.OnClickListener listener = new View.OnClickListener() {
      @Override public void onClick(View v) {
        if (!subscriber.isUnsubscribed()) {
          subscriber.onNext(view);
        }
      }
    };
    view.setOnClickListener(listener);

    subscriber.add(new MainThreadSubscription() {
      @Override protected void onUnsubscribe() {
        view.setOnClickListener(null);
      }
    });
  }
}

具體使用:

@Override
public void initAction() {
     RxViewHelp.clicks(this, mTagTv, image, mFinishBtn);
}

@Override
public void call(View view) {
    if (view == mTagTv) {
          
    } else if (view == image) {

    } else{

    }
}

Rxjava2實(shí)現(xiàn)

RxView.java

package com.itbird.utils;

import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import android.view.View;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import static com.itbird.utils.Preconditions.checkNotNull;
import static com.itbird.utils.Preconditions.checkUiThread;

/**
 * 利用Rxjava防止抖動(dòng) and 重復(fù)點(diǎn)擊
 * Created by xfkang on 2018/3/24.
 */

public class RxView {
    /**
     * 防止重復(fù)點(diǎn)擊
     *
     * @param target 目標(biāo)view
     * @param action 監(jiān)聽器
     */
    public static void setOnClickListeners(final Action1<View> action, @NonNull View... target) {
        for (View view : target) {
            RxView.onClick(view).throttleFirst(500, TimeUnit.MILLISECONDS).subscribe(new Consumer<View>() {
                @Override
                public void accept(@io.reactivex.annotations.NonNull View view) throws Exception {
                    action.onClick(view);
                }
            });
        }
    }

    /**
     * 監(jiān)聽onclick事件防抖動(dòng)
     *
     * @param view
     * @return
     */
    @CheckResult
    @NonNull
    private static Observable<View> onClick(@NonNull View view) {
        checkNotNull(view, "view == null");
        return Observable.create(new ViewClickOnSubscribe(view));
    }

//    @CheckResult
//    @NonNull
//    public static <T extends Adapter> Observable<AdapterViewItemClickEvent> itemClickEvents(
//            @NonNull RecyclerAdapter<?> view) {
//        checkNotNull(view, "view == null");
//        return Observable.create(new AdapterViewItemClickEventOnSubscribe(view));
//    }

    /**
     * onclick事件防抖動(dòng)
     * 返回view
     */
    private static class ViewClickOnSubscribe implements ObservableOnSubscribe<View> {
        private View view;

        public ViewClickOnSubscribe(View view) {
            this.view = view;
        }

        @Override
        public void subscribe(@io.reactivex.annotations.NonNull final ObservableEmitter<View> e) throws Exception {
            checkUiThread();

            View.OnClickListener listener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!e.isDisposed()) {
                        e.onNext(view);
                    }
                }
            };
            view.setOnClickListener(listener);
        }
    }

    /**
     * A one-argument action. 點(diǎn)擊事件轉(zhuǎn)發(fā)接口
     *
     * @param <T> the first argument type
     */
    public interface Action1<T> {
        void onClick(T t);
    }
}

Preconditions.java

/*
 * 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.itbird.utils;

import android.os.Looper;

public final class Preconditions {
  public static void checkArgument(boolean assertion, String message) {
    if (!assertion) {
      throw new IllegalArgumentException(message);
    }
  }

  public static <T> T checkNotNull(T value, String message) {
    if (value == null) {
      throw new NullPointerException(message);
    }
    return value;
  }

  public static void checkUiThread() {
    if (Looper.getMainLooper() != Looper.myLooper()) {
      throw new IllegalStateException(
          "Must be called from the main thread. Was: " + Thread.currentThread());
    }
  }

  private Preconditions() {
    throw new AssertionError("No instances.");
  }
}

具體使用:

1.為多個(gè)控件一起注冊(cè)onClick事件

setOnClickListeners.png

2.onClick事件具體方法

onClick.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末矮烹,一起剝皮案震驚了整個(gè)濱河市越庇,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌奉狈,老刑警劉巖卤唉,帶你破解...
    沈念sama閱讀 211,042評(píng)論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異仁期,居然都是意外死亡桑驱,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 89,996評(píng)論 2 384
  • 文/潘曉璐 我一進(jìn)店門跛蛋,熙熙樓的掌柜王于貴愁眉苦臉地迎上來熬的,“玉大人,你說我怎么就攤上這事赊级⊙嚎颍” “怎么了?”我有些...
    開封第一講書人閱讀 156,674評(píng)論 0 345
  • 文/不壞的土叔 我叫張陵理逊,是天一觀的道長(zhǎng)橡伞。 經(jīng)常有香客問我,道長(zhǎng)挡鞍,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,340評(píng)論 1 283
  • 正文 為了忘掉前任预烙,我火速辦了婚禮墨微,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘扁掸。我一直安慰自己翘县,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,404評(píng)論 5 384
  • 文/花漫 我一把揭開白布谴分。 她就那樣靜靜地躺著锈麸,像睡著了一般。 火紅的嫁衣襯著肌膚如雪牺蹄。 梳的紋絲不亂的頭發(fā)上忘伞,一...
    開封第一講書人閱讀 49,749評(píng)論 1 289
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼氓奈。 笑死翘魄,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的舀奶。 我是一名探鬼主播暑竟,決...
    沈念sama閱讀 38,902評(píng)論 3 405
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼育勺!你這毒婦竟也來了但荤?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,662評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤涧至,失蹤者是張志新(化名)和其女友劉穎腹躁,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體化借,經(jīng)...
    沈念sama閱讀 44,110評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡潜慎,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,451評(píng)論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了蓖康。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片铐炫。...
    茶點(diǎn)故事閱讀 38,577評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖蒜焊,靈堂內(nèi)的尸體忽然破棺而出倒信,到底是詐尸還是另有隱情,我是刑警寧澤泳梆,帶...
    沈念sama閱讀 34,258評(píng)論 4 328
  • 正文 年R本政府宣布鳖悠,位于F島的核電站,受9級(jí)特大地震影響优妙,放射性物質(zhì)發(fā)生泄漏乘综。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,848評(píng)論 3 312
  • 文/蒙蒙 一套硼、第九天 我趴在偏房一處隱蔽的房頂上張望卡辰。 院中可真熱鬧,春花似錦邪意、人聲如沸九妈。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,726評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)萌朱。三九已至,卻和暖如春策菜,著一層夾襖步出監(jiān)牢的瞬間晶疼,已是汗流浹背酒贬。 一陣腳步聲響...
    開封第一講書人閱讀 31,952評(píng)論 1 264
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留冒晰,地道東北人同衣。 一個(gè)月前我還...
    沈念sama閱讀 46,271評(píng)論 2 360
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像壶运,于是被迫代替她去往敵國(guó)和親耐齐。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,452評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容