RxJava:RxBinding

RxJava:RxBinding_第1张图片
Photo by Peter Hershey on Unsplash

学无止境

添加依赖
RxBinding库是根据其所支持控件在Android平台的位置而单独分离的。

//Platform bindings:
compile 'com.jakewharton.rxbinding2:rxbinding:2.0.0'

//'support-v4' library bindings:
compile 'com.jakewharton.rxbinding2:rxbinding-support-v4:2.0.0'

//'appcompat-v7' library bindings:
compile 'com.jakewharton.rxbinding2:rxbinding-appcompat-v7:2.0.0'

//'design' library bindings:
compile 'com.jakewharton.rxbinding2:rxbinding-design:2.0.0'

//'recyclerview-v7' library bindings:
compile 'com.jakewharton.rxbinding2:rxbinding-recyclerview-v7:2.0.0'

//'leanback-v17' library bindings:
compile 'com.jakewharton.rxbinding2:rxbinding-leanback-v17:2.0.0'

应用示例:

按钮的长按 / 点击时间监听

        RxView.longClicks(mButton)//长按
//                .clicks(mButton)//点击
                .subscribe(new Consumer() {
                    @Override
                    public void accept(Object o) throws Exception {
                        Log.d("flag", "长按点击了!");
                    }
                });
 
 

Button 防抖处理

        RxView.clicks(mButton)
                //两秒钟之内只取第一个点击事件,防抖操作
                .throttleFirst(2, TimeUnit.SECONDS)
                .subscribe(new Consumer() {
                    @Override
                    public void accept(Object o) throws Exception {
                        Log.d("flag", "点击了!");
                    }
                });
 
 

实现原理
RxView.clicks()为例,clicks()源码如下所示,

  @CheckResult @NonNull
  public static Observable clicks(@NonNull View view) {
    checkNotNull(view, "view == null");
    return new ViewClickObservable(view);
  }
 
 

返回一个ViewClickObservable对象,参数是传入的view,然后来学习一下ViewClickObservable这个类,

final class ViewClickObservable extends Observable {
  private final View view;

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

  @Override protected void subscribeActual(Observer observer) {
    if (!checkMainThread(observer)) {
      return;
    }
    Listener listener = new Listener(view, observer);
    observer.onSubscribe(listener);
    view.setOnClickListener(listener);
  }

  static final class Listener extends MainThreadDisposable implements OnClickListener {
    private final View view;
    private final Observer observer;

    Listener(View view, Observer observer) {
      this.view = view;
      this.observer = observer;
    }

    @Override public void onClick(View v) {
      if (!isDisposed()) {
        observer.onNext(Notification.INSTANCE);
      }
    }

    @Override protected void onDispose() {
      view.setOnClickListener(null);
    }
  }
}
 
 

首先看是Listener这个类,它继承了MainThreadDisposable并且实现了OnClickListener,在onClick()中订阅者对这个事件进行了回调。同时onDispose()中停止对view的监听;
而真正的订阅发生在在subscribeActual()中,listener订阅了上游的observer,并且设置了view的监听事件;

除此之外,textChanges()longClicks()也是类似这样进一步的封装;

对于RxJava的学习才刚刚开始!
RxJava:RxBus事件总线
RxJava:RxBinding
RxJava:Rxlifecycle

你可能感兴趣的:(RxJava:RxBinding)