Retrofit基础上添加反射方法

2020-06-19  本文已影响0人  Android刘东

1.方法

     /***
     *  @param methodName 方法名
     * @param args 方法参数值
     */
    public <T> Disposable getHttp(String methodName, String[] args, final AHttpBack mHttpBack) {
        try {
            Class<?>[] nClass = new Class[args.length];
            for (int i = 0; i < args.length; i++) {
                nClass[i] = String.class;
            }
            Object object = HttpMethods.getInstance().getApiService().getClass()
                    .getMethod(methodName, nClass)
                    .invoke(HttpMethods.getInstance().getApiService(), args);
            if (object instanceof Observable) {
                Observable<T> mObservable = (Observable<T>) object;
                return mObservable.compose(schedulersTransformer()).subscribe(new Consumer<T>() {
                    @Override
                    public void accept(T t) throws Exception {
                        mHttpBack.onSuccess(t);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        mHttpBack.onExceptions(throwable);
                    }
                });

            }
            return null;
        } catch (Exception e) {
            mHttpBack.onExceptions(e);
            return null;
        }

    }

    public  ObservableTransformer schedulersTransformer() {
        return new ObservableTransformer() {
            @Override
            public ObservableSource apply(Observable upstream) {
                return upstream.subscribeOn(Schedulers.io())
                        .unsubscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }

上一篇下一篇

猜你喜欢

热点阅读