精华内容
下载资源
问答
  • RxAndroid

    2021-03-29 17:40:33
    RxAndroid 只是提供一个能切换到 Android 主线程线程调度器。 其实 RxAndroid 的核心就是 Handler。 private static final class MainHolder { static final Scheduler DEFAULT = new HandlerScheduler(new ...

    RxAndroid 提供一个能切换到 Android 主线程线程调度器。
    其实 RxAndroid 的核心就是 Handler。

    private static final class MainHolder {
    static final Scheduler DEFAULT = new HandlerScheduler(new Handler(Looper.getMainLooper()));
    }

    private static final Scheduler MAIN_THREAD = RxAndroidPlugins.initMainThreadScheduler(
    new Callable() {
    @Override public Scheduler call() throws Exception {
    return MainHolder.DEFAULT;
    }
    }
    );

    public static Scheduler mainThread() {
    return RxAndroidPlugins.onMainThreadScheduler(MAIN_THREAD);
    }

    public static Scheduler from(Looper looper) {
    if (looper == null) throw new NullPointerException(“looper == null”);
    return new HandlerScheduler(new Handler(looper));
    }

    展开全文
  • rxandroid

    2020-03-31 14:10:17
    @GET("work/wdxcjlb/list") Observable<BaseObjectBean<PatrolListBean>> getPatrolList(@Query("start") String start, @Query("end") String end, @Query("limit") int limit, @Query("page") int pa....
    public class URLConstant {
        public static String getBaseUrl() {
            if (!BuildConfig.DEBUG) {
    /
                return "http:";
            } else {
    //            return "http:";
    
            }
        }
    }
    @GET("work/wdxcjlb/list")
    Observable<BaseObjectBean<PatrolListBean>> getPatrolList(@Query("start") String start, @Query("end") String end, @Query("limit") int limit, @Query("page") int page);
    /**
     * 三查六巡----->查询列表
     *
     * @param start    开始时间
     * @param end      结束时间
     * @param observer
     */
    public static void getPatrolList(String start, String end, int limit, int page, CustomObserver<BaseObjectBean<PatrolListBean>> observer) {
        requestHandler(mNetApi.getPatrolList(start, end, limit, page))
                .subscribe(observer);
    }
    
      /**
         * 联网线程切换,也可做返回数据的统一处理
         */
        private static <RESPONSE> Observable<RESPONSE> requestHandler(Observable<RESPONSE> response) {
            return response.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread());
        }
    ​
    public class Client {
    
        private static OkHttpClient mOkHttpClient;
    
        /**
         * 创建OkHttpClient
         */
        public static OkHttpClient getOkHttp() {
    
            if (mOkHttpClient == null) {
                synchronized (OkHttpClient.class) {
                    if (mOkHttpClient == null) {
                        int cacheSize = 10 * 1024 * 1024; // 10 MiB
                        Cache cache = new Cache(PoliceAssistantApplication.getContext().getCacheDir(), cacheSize);
                        mOkHttpClient = new OkHttpClient.Builder()
                                .addNetworkInterceptor(new TokenHeaderInterceptor())
                                .addNetworkInterceptor(new ParametersInterceptor())
                                .retryOnConnectionFailure(true)//断网重连
                                .cache(cache)
                                .connectTimeout(10, TimeUnit.SECONDS)
                                .readTimeout(30, TimeUnit.SECONDS)
                                .writeTimeout(30, TimeUnit.SECONDS)
                                .build();
                    }
                }
            }
            return mOkHttpClient;
        }
    }
    
    ​

     

    public class Retrofits {
    
        private static Retrofit mRetrofit;
    
        /**
         * 创建Retrofit
         *
         * @return
         */
        public static Retrofit get() {
            if (mRetrofit == null) {
                synchronized (Retrofit.class) {
                    mRetrofit = new Retrofit.Builder()
                            .client(Client.getOkHttp())
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            .baseUrl(URLConstant.getBaseUrl())
                            .build();
                }
            }
            return mRetrofit;
    
        }
    
        /**
         * 判断是否有网络连接
         */
        public static void onNetWorkNotAvailable() {
            if (!NetUtils.isAvailable(PoliceAssistantApplication.getContext())) {
                if (AppManager.getInstance().getActivityStackTop() != null) {
                    try {
                        ((BaseActivity) AppManager.getInstance().getActivityStackTop()).showNetErrorDialog();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    
    
        /**
         * 返回接口类
         *
         * @param tClass 接口
         * @param <T>
         * @return
         */
        public static <T> T getClass(Class<T> tClass) {
            onNetWorkNotAvailable();
            return get().create(tClass);
        }
    }
    public abstract class CustomObserver<T> implements Observer<T> {
    
        private Context mContext;
        private CustomLoadDialog dialog;
        private boolean isShow = false;
    
        public CustomObserver() {
        }
    
        public CustomObserver(Context mContext,  boolean isShow) {
            this.mContext = mContext;
            this.isShow = isShow;
        }
    
        @Override
        public void onSubscribe(Disposable d) {
            onBefore(d);
            if (isShow) {
                dialog = new CustomLoadDialog(mContext);
                dialog.setCanceledOnTouchOutside(false);
                dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialogInterface) {
                        // 对话框取消 直接停止执行请求
                        if (!d.isDisposed()) {
                            d.dispose();
                        }
                    }
                });
                dialog.show();
            }
        }
    
    
        @Override
        public void onNext(T value) {
            if (null == value) {
                onFail(ExceptionHandle.ERROR.NULL_ERROR);
            } else {
                onSuccess(value);
            }
        }
    
    
        @Override
        public void onError(Throwable e) {
            if (isShow) {
                if (dialog != null)
                    dialog.dismiss();
            }
            e.printStackTrace();
            ExceptionHandle.ERROR error = ExceptionHandle.handleException(e);
            onFail(error);
        }
    
    
        @Override
        public void onComplete() {
            onCompleted();
            if (isShow) {
                if (dialog != null)
                    dialog.dismiss();
            }
        }
    
        protected void onBefore(Disposable d) {
        }
    
        protected void onCompleted() {
        }
    
        protected abstract void onSuccess(T bean);
    
        protected abstract void onFail(ExceptionHandle.ERROR error);
    }
      /**
         * 请求数据
         *
         * @param start
         * @param end
         */
        public void getData(String start, String end, int limit, int page) {
            NetService.getPatrolList(start, end, limit, page, new CustomObserver<BaseObjectBean<PatrolListBean>>(this, true) {
                @Override
                protected void onSuccess(BaseObjectBean<PatrolListBean> bean) {
                    if (bean.getCode() != 0) {
                        LogUtils.i(bean.getMsg());
                    } else if (bean.getData().getPage() != null && bean.getData().getPage().getList() != null && bean.getData().getPage().getList().size() > 0) {
                        mCommonAdapter.setDate(bean.getData().getPage().getList());
                    } else {
                        ToastUtils.getInstance(PatrolActivity.this).showMessage(getString(R.string.no_data));
                        mCommonAdapter.clearList();
                        listView.setAdapter(mCommonAdapter);
                    }
                }
    
                @Override
                protected void onFail(ExceptionHandle.ERROR error) {
                    LogUtils.i(error + "");
                }
            });
        }
    
    * 描述:公共参数的拦截器
     */
    public class HttpCommonInterceptor implements Interceptor {
    
        private String TAG = "cl";
    
        private Map<String, String> mHeaderParamsMap = new HashMap<>();
    
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request oldRequest = chain.request();
            // 添加新的参数,添加到url 中
             /*HttpUrl.Builder authorizedUrlBuilder = oldRequest.url().newBuilder()
            .scheme(oldRequest.url().scheme()) .host(oldRequest.url().host());*/
            // 新的请求
            Request.Builder requestBuilder = oldRequest.newBuilder();
            requestBuilder.method(oldRequest.method(), oldRequest.body());
            //添加公共参数,添加到header中
            if (mHeaderParamsMap.size() > 0) {
                for (Map.Entry<String, String> parms : mHeaderParamsMap.entrySet()) {
                    requestBuilder.header(parms.getKey(), parms.getValue());
                }
            }
            Request newBuild = requestBuilder.build();
            return chain.proceed(newBuild);
        }
    
        public static class Builder {
            HttpCommonInterceptor mHttpCommonInterceptor;
    
            public Builder() {
                mHttpCommonInterceptor = new HttpCommonInterceptor();
            }
    
            public Builder addHeaderParams(String key, String value) {
                mHttpCommonInterceptor.mHeaderParamsMap.put(key, value);
                return this;
            }
    
            public Builder addHeaderParams(String key, int value) {
                return addHeaderParams(key, String.valueOf(value));
            }
    
            public Builder addHeaderParams(String key, float value) {
                return addHeaderParams(key, String.valueOf(value));
            }
    
            public Builder addHeaderParams(String key, long value) {
                return addHeaderParams(key, String.valueOf(value));
            }
    
            public Builder addHeaderParams(String key, double value) {
                return addHeaderParams(key, String.valueOf(value));
            }
    
            public HttpCommonInterceptor build() {
                return mHttpCommonInterceptor;
            }
        }
    public class TokenHeaderInterceptor implements Interceptor {
    
        @Override
        public Response intercept(Chain chain) throws IOException {
            String loginToken = SharePrefsHelper.getInstance().getString(SharePrefsConstants.TOKEN, "");
            if (loginToken.isEmpty()) {
                Request originalRequest = chain.request();
                return chain.proceed(originalRequest);
            } else {
                Request originalRequest = chain.request();
                Request updateRequest = originalRequest.newBuilder().header("token", loginToken).build();
                return chain.proceed(updateRequest);
            }
        }
    
    }
    * 描述:打印参数拦截器
     */
    public class ParametersInterceptor implements Interceptor {
    
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            long startTime = System.currentTimeMillis();
            StringBuilder requestSb = new StringBuilder(String.format("发送%s请求 %s on %s%n%s", request.method(), request.url(), chain.connection(), request.headers()));
            RequestBody requestBody = request.body();
            if (requestBody != null) {
                if (requestBody.contentType() != null)
                    requestSb.append("\r\nContent-Type:").append(requestBody.contentType());
                if (requestBody.contentLength() != -1)
                    requestSb.append("\r\nContent-Length:").append(requestBody.contentLength());
                //参数
                Buffer buffer = new Buffer();
                requestBody.writeTo(buffer);
                Charset charset = Charset.forName("utf-8");
                MediaType contentType = requestBody.contentType();
                if (contentType != null) {
                    Charset charset1 = contentType.charset(Charset.forName("utf-8"));
                    if (charset1 != null) charset = charset1;
                }
                requestSb.append("\r\n").append(buffer.readString(charset));
            }
            Log.i("mio", requestSb.toString());
            LogUtils.i(requestSb.toString());
            Response response = chain.proceed(request);
    
            long endTime = System.currentTimeMillis();
            ResponseBody responseBody = response.peekBody(1024 * 1024);
            Log.i("mio", String.format("接收响应:[%s] %n返回json:%s  %.1fms%n%s", response.request().url(),
                    responseBody.string(), ((float) (endTime - startTime)) / 1000, request.headers()));
            return response;
        }
    }

     

    //Gson
    implementation 'com.google.code.gson:gson:2.7'
    //Retrofit
    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
    //转换器,请求结果转换成Model
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'
    //RxJava
    implementation 'io.reactivex.rxjava2:rxjava:2.1.13'
    //RxAndroid
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
    //日志拦截器
    implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
    //FastJson
    implementation 'com.alibaba:fastjson:1.2.57'
    展开全文
  • RXAndroid

    2017-10-23 14:54:01
    1.基本模式 1)new一个观察者observer Observer observer = new Observer() {  @Override  public void onSubscribe(@NonNull Disposable d) {   }  @Override

    1.基本模式

    1)创建观察者observer

    Observer<String> observer = new Observer<String>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {
                    
                }


                @Override
                public void onNext(@NonNull String s) {
                    Log.d("log",s);
                }


                @Override
                public void onError(@NonNull Throwable e) {


                }


                @Override
                public void onComplete() {


                }
            };

    2)创建被观察着observable 

    Observable<String> observable = Observable.create(new ObservableOnSubscribe<String>() {
                @Override
                public void subscribe(@NonNull ObservableEmitter<String> e) throws Exception {
                    e.onNext("coco");
                    e.onNext("cole");
                }
            });

    3)建立订阅关系subscribe()

    observable.subscribe(observer);


    2.异步控制

    observable.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(observer);


    subscribeOn:发布线程 onSubscribe()方法所在线程

    observeOn:回调线程 onNext()方法所在线程


    3.操作符

    1) map  对象转换

    ex.将文件路径转成文件输出

    observable.map(new Function<String, File>() {
                @Override
                public File apply(@NonNull String s) throws Exception {
                    return new File(s);
                }
            });

    2) filter 筛选

    ex.筛选出文件名包含cococola的文件

    observable.filter(new Predicate<String>() {
                @Override
                public boolean test(@NonNull String s) throws Exception {

    //该项return true 为显示,false为不显示
                    return "cococola".equals(s);
                };

    3) 等等等等   

    4) 操作符需连起来写


    展开全文
  • RxAndroid学习

    2019-05-01 00:08:41
    RxAndroid

    RxAndroid

    展开全文
  • RxJava_RxAndroid_Demo:RxJava RxAndroid演示
  • RxAndroid 教程

    2018-11-15 06:45:47
    RxAndroid 教程
  • RxAndroid 使用

    2018-11-20 15:06:54
    RxAndroid GitHub地址: ...RxAndroid环境只需求要引入如下项目即可,我们不但需要RxAndroid项目还需要RxJava项目。 implementation 'io.reactivex.rxjava2:rxandroid:2.1.0' implementati...
  • Learning-Rxandroid, 通过PPT和示例一起学习和使用 RxAndroid 学习 RxAndroid因为 RxJava 。RxAndroid和创建这个项目的RxBinding 。 RxAndroid制作程序编码更为简单,另外,对于我的项目的观察者 Pattern 设计,提高...
  • rxandroid-2.0.1.aar

    2021-02-08 09:52:56
    rxandroid-2.0.1.aar
  • RxAndroid教程

    千次阅读 2017-06-26 15:40:32
    原文链接:...面向初学者的一篇翻译友好的 RxJava / RxAndroid 入门教程。 —— 由Jamweak分享 原文地址:RxAndroid Tutorial原文作者:Artem Kholodnyi译文出自:掘金翻译计划
  • 初识rxAndroid

    2017-05-05 11:23:14
    rxjava/rxandroid开发所需jar包:点击下载 依赖库: compile '... compile 'io.reactivex:rxandroid:1.1.0' // RxAndroid compile 'io.reactivex:rxjava:1.1.0' // 推荐同时加载RxJava 1,
  • Rxjava RxAndroid

    2019-09-20 14:55:39
    api 'io.reactivex.rxjava2:rxandroid:2.1.1' api 'io.reactivex.rxjava2:rxjava:2.2.12' RxJava: 1、引入java 1.8,或者在根目录做统一管理也可以 2、被观察者跟观察者的处理 Observable.just("123")....
  • RxAndroid/RxJava jar

    千次下载 热门讨论 2016-02-24 15:33:12
    RxAndroid RxJava jar包
  • rxandroid 基础知识

    2021-02-25 16:57:11
    在Android 中, 使用 rxandroid , rxandroid和rxJava的关系是,rxandroid包 依赖rxJava包,在其功能上增加了一些Android特有功能,项目中如果不需要指定rxJava包的版本,只需引入rxandroid包即可,如果需要更改 rxandroid...
  • RxPractice:RxAndroid练习
  • 老罗RxAndroid授课ppt

    2016-12-11 19:09:05
    老罗RxAndroid授课资料截图
  • 这么理解RxAndroid之一认识RxAndroid

    千次阅读 2016-08-28 01:33:35
    前言我目前还在边学别写,极有可能出现很多理解不到位而闹的笑话,请留言指正。 我学习的链接就是gank.io上扔物...RxAndroid的简单实现什么是RxAndroid?要说RxAndroid还得先说RxJava,大家可以从这2个词看出来Rx是相
  • 认识RxAndroid

    2017-02-24 18:41:27
    这么理解RxAndroid之一认识RxAndroid 标签: androidRxAndroid 2016-08-28 01:33 802人阅读 评论(0) 收藏 举报 本文章已收录于: 分类: Android(13) 作者同类文章X ...
  • RXAndroid入门

    2016-08-15 15:31:07
    使用如下android需要在build.gradle中加入compile 'io.reactivex:rxandroid:1.2.1' 一、在UI现场观察 //需要导入compile 'io.reactivex:rxandroid:1.2.1' Observable averageObservable = MathObservable.sumI
  • RxAndroid 常见用法

    千次阅读 2016-05-11 22:04:05
    RxAndroid 常见用法在项目里面添加 compile 'io.reactivex:rxandroid:1.1.0' // Because RxAndroid releases are few and far between, it is recommended you also // explicitly depend on RxJava's latest ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 2,954
精华内容 1,181
关键字:

rxandroid