使用Rxjava2防止抖动 and 重复点击

最近项目中为了解决按钮重复点击问题,搜索过程中,发现Rxjava居然可以实现这个功能,但是问题随之而来,网上给出的所有Rxjava的解决方案都是基于Rxjava 1.0版本的,而项目工程中使用的Rxjava2。话不多说,直接上代码,各位看官自己看吧。

具体API区别可以参考之前的文章:https://www.jianshu.com/p/d53463e1c3d6

Rxjava1实现

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 action, @NonNull View... views) {
        for (View view : views) {
            RxView.clicks(view).throttleFirst(500, TimeUnit.MILLISECONDS).subscribe(action);
        }
    }

    public static Observable 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() {
                    @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 {
    /**
     * 监听onclick事件防抖动
     *
     * @param view
     * @return
     */
    @CheckResult
    @NonNull
    public static Observable clicks(@NonNull View view) {
        checkNotNull(view, "view == null");
        return Observable.create(new ViewClickOnSubscribe(view));
    }

    @CheckResult
    @NonNull
    public static  Observable 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 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事件防抖动
 * 返回view
 */
final class ViewClickOnSubscribe implements Observable.OnSubscribe {
  final View view;

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

  @Override
  public void call(final Subscriber 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实现

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防止抖动 and 重复点击
 * Created by xfkang on 2018/3/24.
 */

public class RxView {
    /**
     * 防止重复点击
     *
     * @param target 目标view
     * @param action 监听器
     */
    public static void setOnClickListeners(final Action1 action, @NonNull View... target) {
        for (View view : target) {
            RxView.onClick(view).throttleFirst(500, TimeUnit.MILLISECONDS).subscribe(new Consumer() {
                @Override
                public void accept(@io.reactivex.annotations.NonNull View view) throws Exception {
                    action.onClick(view);
                }
            });
        }
    }

    /**
     * 监听onclick事件防抖动
     *
     * @param view
     * @return
     */
    @CheckResult
    @NonNull
    private static Observable onClick(@NonNull View view) {
        checkNotNull(view, "view == null");
        return Observable.create(new ViewClickOnSubscribe(view));
    }

//    @CheckResult
//    @NonNull
//    public static  Observable itemClickEvents(
//            @NonNull RecyclerAdapter view) {
//        checkNotNull(view, "view == null");
//        return Observable.create(new AdapterViewItemClickEventOnSubscribe(view));
//    }

    /**
     * onclick事件防抖动
     * 返回view
     */
    private static class ViewClickOnSubscribe implements ObservableOnSubscribe {
        private View view;

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

        @Override
        public void subscribe(@io.reactivex.annotations.NonNull final ObservableEmitter 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. 点击事件转发接口
     *
     * @param  the first argument type
     */
    public interface Action1 {
        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 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.为多个控件一起注册onClick事件

setOnClickListeners.png

2.onClick事件具体方法

使用Rxjava2防止抖动 and 重复点击_第1张图片
onClick.png

你可能感兴趣的:(使用Rxjava2防止抖动 and 重复点击)