关于 RxJava2CallAdapterFactory

今天 在看谷歌最新的框架的时候 发现有一段 有些疑问的代码

 public LiveData> loadUser(String login) {
        return new NetworkBoundResource(appExecutors) {

            //...

            @NonNull
            @Override
            protected LiveData> createCall() {

                // 这里直接返回 并没有像我们常写的那样  需要拼接以下代码
                //    subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())

                return githubService.getUser(login);  //网络请求
        
            }
        }.asLiveData();
    }

然后 看了 LiveDataCallAdapterFactory 类 对应 RxJava2CallAdapterFactory



//...
 @Override
    public CallAdapter get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
        if (getRawType(returnType) != LiveData.class) {
            return null;
        }
        Type observableType = getParameterUpperBound(0, (ParameterizedType) returnType);
        Class rawObservableType = getRawType(observableType);
        if (rawObservableType != ApiResponse.class) {
            throw new IllegalArgumentException("type must be a resource");
        }
        if (! (observableType instanceof ParameterizedType)) {
            throw new IllegalArgumentException("resource must be parameterized");
        }
        Type bodyType = getParameterUpperBound(0, (ParameterizedType) observableType);
        return new LiveDataCallAdapter<>(bodyType);  // 发现了这个类
    }

然后 再接着看 LiveDataCallAdapter 这个类的代码并不多 全文就在下面

public class LiveDataCallAdapter implements CallAdapter>> {
    private final Type responseType;
    public LiveDataCallAdapter(Type responseType) {
        this.responseType = responseType;
    }

    @Override
    public Type responseType() {
        return responseType;
    }

    @Override
    public LiveData> adapt(Call call) {
        return new LiveData>() {
            AtomicBoolean started = new AtomicBoolean(false);
            @Override
            protected void onActive() {
                super.onActive();
                if (started.compareAndSet(false, true)) {
                    //最终看到这里    全明白了  它在这里 直接  异步执行了  请求方法
                    call.enqueue(new Callback() {
                        @Override
                        public void onResponse(Call call, Response response) {
                            postValue(new ApiResponse<>(response));
                        }

                        @Override
                        public void onFailure(Call call, Throwable throwable) {
                            postValue(new ApiResponse(throwable));
                        }
                    });
                }
            }
        };
    }
}

最终我们发现 原来请求是在这个类里面执行的 然后 我就想着看 RxJava2CallAdapterFactory 里对应LiveDataCallAdapter 的类是怎么写的
我们再看回 RxJava2CallAdapterFactory 懂英语的看看英语也应该看明白了一些 有创建同步 、异步、还有根据Scheduler的

 /**
   * Returns an instance which creates synchronous observables that do not operate on any scheduler
   * by default.
   */
  public static RxJava2CallAdapterFactory create() {
    return new RxJava2CallAdapterFactory(null, false);
  }

  /**
   * Returns an instance which creates asynchronous observables. Applying
   * {@link Observable#subscribeOn} has no effect on stream types created by this factory.
   */
  public static RxJava2CallAdapterFactory createAsync() {
    return new RxJava2CallAdapterFactory(null, true);
  }

  /**
   * Returns an instance which creates synchronous observables that
   * {@linkplain Observable#subscribeOn(Scheduler) subscribe on} {@code scheduler} by default.
   */
  @SuppressWarnings("ConstantConditions") // Guarding public API nullability.
  public static RxJava2CallAdapterFactory createWithScheduler(Scheduler scheduler) {
    if (scheduler == null) throw new NullPointerException("scheduler == null");
    return new RxJava2CallAdapterFactory(scheduler, false);
  }

  // ....

//不管上面选择的是什么最后都是返回 RxJava2CallAdapter
 return new RxJava2CallAdapter(responseType, scheduler, isAsync, isResult, isBody, isFlowable,
        isSingle, isMaybe, false);

我们也发现了 LiveDataCallAdapter 对应的类就是 RxJava2CallAdapter
RxJava2CallAdapter同样 代码也不多

final class RxJava2CallAdapter implements CallAdapter {
  private final Type responseType;
  private final @Nullable Scheduler scheduler;
  private final boolean isAsync;
  private final boolean isResult;
  private final boolean isBody;
  private final boolean isFlowable;
  private final boolean isSingle;
  private final boolean isMaybe;
  private final boolean isCompletable;

  RxJava2CallAdapter(Type responseType, @Nullable Scheduler scheduler, boolean isAsync,
      boolean isResult, boolean isBody, boolean isFlowable, boolean isSingle, boolean isMaybe,
      boolean isCompletable) {
    this.responseType = responseType;
    this.scheduler = scheduler;
    this.isAsync = isAsync;
    this.isResult = isResult;
    this.isBody = isBody;
    this.isFlowable = isFlowable;
    this.isSingle = isSingle;
    this.isMaybe = isMaybe;
    this.isCompletable = isCompletable;
  }

  @Override public Type responseType() {
    return responseType;
  }

  @Override public Object adapt(Call call) {
    Observable> responseObservable = isAsync
        //异步时 用这个类
        ? new CallEnqueueObservable<>(call)
      //同步时 用这个类
        : new CallExecuteObservable<>(call);

    Observable observable;
    if (isResult) {
      observable = new ResultObservable<>(responseObservable);
    } else if (isBody) {
      observable = new BodyObservable<>(responseObservable);
    } else {
      observable = responseObservable;
    }

//createWithScheduler 时  传的 scheduler
    if (scheduler != null) {
    //看到这句  发现了 原来我们以前一直写着的那句 觉得是累赘  又不得不写的代码   
    //原来 RxJava2CallAdapterFactory 早就有选择给我们用了  而一直没有去发现
      observable = observable.subscribeOn(scheduler);
    }

    if (isFlowable) {
      return observable.toFlowable(BackpressureStrategy.LATEST);
    }
    if (isSingle) {
      return observable.singleOrError();
    }
    if (isMaybe) {
      return observable.singleElement();
    }
    if (isCompletable) {
      return observable.ignoreElements();
    }
    return observable;
  }
}

顺便看看 CallEnqueueObservable 类

final class CallEnqueueObservable extends Observable> {
  private final Call originalCall;

  CallEnqueueObservable(Call originalCall) {
    this.originalCall = originalCall;
  }

  @Override protected void subscribeActual(Observer> observer) {
    // Since Call is a one-shot type, clone it for each new observer.
    Call call = originalCall.clone();
    CallCallback callback = new CallCallback<>(call, observer);
    observer.onSubscribe(callback);
    //异步执行  这是长尾巴  求关注   看下面这行代码就够了
    call.enqueue(callback);
  }

  private static final class CallCallback implements Disposable, Callback {
    private final Call call;
    private final Observer> observer;
    boolean terminated = false;

    CallCallback(Call call, Observer> observer) {
      this.call = call;
      this.observer = observer;
    }
    //..
  }
}

CallExecuteObservable 类

final class CallExecuteObservable extends Observable> {
  private final Call originalCall;

  CallExecuteObservable(Call originalCall) {
    this.originalCall = originalCall;
  }

  @Override protected void subscribeActual(Observer> observer) {
    // Since Call is a one-shot type, clone it for each new observer.
    Call call = originalCall.clone();
    observer.onSubscribe(new CallDisposable(call));

    boolean terminated = false;
    try {
   //这里同步执行   这是长尾巴  求关注   看下面这行代码就够了
      Response response = call.execute();
    //...
    } catch (Throwable t) {
    //...
      }
    }
  }

  private static final class CallDisposable implements Disposable {
    private final Call call;

    CallDisposable(Call call) {
      this.call = call;
    }

    @Override public void dispose() {
      call.cancel();
    }

    @Override public boolean isDisposed() {
      return call.isCanceled();
    }
  }
}

其实 上面看得那么多 最后 其实 就只是想说以后写成下面那样 可以让你每次写网络请求少写几个单词

retrofit = new  Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
                .baseUrl(baseUrl)
                .build();

//以前这样写
githubService.getUser(login)
                      .subscribeOn(Schedulers.io())
                      .observeOn(AndroidSchedulers.mainThread())
                      .subscribe(...)

//现在可以写成
githubService.getUser(login)
                      .observeOn(AndroidSchedulers.mainThread())
                      .subscribe(...)

你可能感兴趣的:(关于 RxJava2CallAdapterFactory)