Android Retrofit 2,RxJava 2精要实例
来源:互联网 发布:itools for mac 编辑:程序博客网 时间:2024/05/19 20:57
本文旨在记录最热门框架的使用及简单实例,起到抛砖引用的目的,若有更复杂需求,还请参考其他资料.
Retrofit 2:
概念:基于OkHtttp封装,基于注解方式,解耦更彻底的HTTP网络请求框架
Retrofit 2+okhttp3使用:
1:添加依赖
compile 'com.squareup.retrofit2:retrofit:2.0.2' compile 'com.squareup.retrofit2:converter-gson:2.0.2' compile 'com.squareup.okhttp3:logging-interceptor:3.2.0' compile 'com.squareup.okhttp3:okhttp:3.3.0' compile 'com.squareup.okio:okio:1.7.0'
2:定义接口
public interface IRegisterService { @FormUrlEncoded @POST("RegisterDataServlet") Call<RegisterBean> createUser(@FieldMap Map<String ,String> params);}
3:初始化Retrofit
mRetrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create(mGson)) .client(mOkHttpClient) .build();
4:初始化OkHttpClient
mOkHttpClient = new OkHttpClient.Builder() .connectTimeout(12, TimeUnit.SECONDS) .writeTimeout(20, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS) .retryOnConnectionFailure(true) .addInterceptor(mHttpLogInterceptor) .addInterceptor(mBaseParamsInterceptor) .addInterceptor(mUrlInterceptor) .cache(cache) .build();
5:请求使用
IRegisterService loginService = mRetrofit .create(IRegisterService.class);Map<String,String> mParamsMap = new HashMap<>();mParamsMap.put("username",userName);mParamsMap.put("password",password);Call<RegisterBean> call = loginService.createUser(mParamsMap);call.enqueue(new Callback<String>() { public void onResponse(Call<RegisterBean> call, Response<RegisterBean> response) { if(response.body().getErrorCode()==1){ Intent intent = new Intent(RegisterActivity.this, LoginActivity.class); startActivity(intent); }else{ Toast.makeText(getBaseContext(),"注册失败",Toast.LENGTH_SHORT).show(); } } public void onFailure(Call<RegisterBean> call, Throwable t) { } });
RxJava 2:
概念:
一个对于构成使用的Java虚拟机观察序列异步和基于事件的程序库,通俗的话就是异步数据传递和处理,并且链式调用(逻辑清晰),可以用rxbus代替Eventbus
视图:
发送源(Flowable,)—–>接收源(subscriber和consumer)
使用:
1:添加依赖
compile 'io.reactivex.rxjava2:rxjava:2.0.0'compile 'org.reactivestreams:reactive-streams:1.0.0'compile 'io.reactivex.rxjava2:rxandroid:2.0.0'
2:Rxjava2和Rxjava1.x差距不小,所以这是Rxjava 2简单实例:
1:map使用---Flowable.subscribe(Consumer)Flowable.just("map") .map(new Function<String, String>() { @Override public String apply(String s) throws Exception { return s + " -aile"; } }) .subscribe(new Consumer<String>() { @Override public void accept(String s) throws Exception { System.out.println(s); } });2:flatMap使用---Flowable.subscribe(Consumer)List<Integer> list = new ArrayList<>();list.add(10);list.add(1);list.add(5);Flowable.just(list) .flatMap(new Function<List<Integer>, Publisher<Integer>>() { @Override public Publisher<Integer> apply(List<Integer> integers) throws Exception { return Flowable.fromIterable(integers); } }) .subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Exception { System.out.println(integer); } });3:filter使用---Flowable.subscribe(Consumer)Flowable.fromArray(1, 20, 5, 0, -1, 8) .filter(new Predicate<Integer>() { @Override public boolean test(Integer integer) throws Exception { return integer.intValue() > 5; } }) .subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Exception { System.out.println(integer); } });4:take使用---Flowable.subscribe(Consumer)Flowable.fromArray(1, 2, 3, 4) .take(2) .subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Exception { System.out.println(integer); } });5:doOnnext使用---Flowable.subscribe(Consumer)Flowable.just(1, 2, 3) .doOnNext(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Exception { System.out.println("保存:" + integer); } }) .subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Exception { System.out.println(integer); } });6:Flowable.subscribe(Subscriber)Flowable.create(new FlowableOnSubscribe<String>() { @Override public void subscribe(FlowableEmitter<String> e) throws Exception { e.onNext("exception:" + (1 / 0)); e.onComplete(); }}, BackpressureStrategy.BUFFER) .subscribe(new Subscriber<String>() { @Override public void onSubscribe(Subscription s) { s.request(1); } @Override public void onNext(String s) { System.out.println(s); } @Override public void onError(Throwable t) { t.printStackTrace(); System.out.println("onError"); } @Override public void onComplete() { System.out.println("on complete"); } });7:线程调度(shedule)---Flowable.subscribe(Consumer)Flowable.create(new FlowableOnSubscribe<String>() { @Override public void subscribe(FlowableEmitter<String> e) throws Exception { e.onNext("将会在3秒后显示"); SystemClock.sleep(3000); e.onNext("ittianyu"); e.onComplete(); }}, BackpressureStrategy.BUFFER) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<String>() { @Override public void accept(String s) throws Exception { Toast.makeText(RxJava2Activity.this, s, Toast.LENGTH_SHORT).show(); } });
Retrofit 2+RxJava 2使用:
1:添加依赖
compile 'io.reactivex.rxjava2:rxjava:2.0.0'compile 'org.reactivestreams:reactive-streams:1.0.0'compile 'io.reactivex.rxjava2:rxandroid:2.0.0'compile 'com.squareup.okhttp3:okhttp:3.4.1'compile 'com.squareup.okio:okio:1.10.0'compile 'com.squareup.retrofit2:retrofit:2.1.0'compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
2:定义Retrofit接口
public interface BaiDuService { @GET("/") Flowable<ResponseBody> getText();}
3:初始化Retrofit
Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://www.baidu.com/") .addCallAdapterFactory(RxJava2CallAdapterFactory.create())// 添加RxJava2的适配器支持 .build();
4:Rxjava方式,调用发送请求
BaiDuService service = retrofit.create(BaiDuService.class);service.getText() .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<ResponseBody>() { public void onSubscribe(Subscription s) { s.request(Long.MAX_VALUE); } public void onNext(ResponseBody s) { Toast.makeText(RxJava2Activity.this, "获取成功", Toast.LENGTH_SHORT).show(); try { System.out.println(s.string()); } catch (IOException e) { e.printStackTrace(); } } public void onError(Throwable t) { t.printStackTrace(); Toast.makeText(RxJava2Activity.this, "获取失败,请检查网络是否畅通", Toast.LENGTH_SHORT).show(); } public void onComplete() { System.out.println("任务结束"); } });
好了,这是简单介绍,具体复杂程度看业务
0 0
- Android Retrofit 2,RxJava 2精要实例
- Android MVP+Retrofit(封装)+RxJava实例
- RxJava开发精要2-为什么是Observables?
- RxJava开发精要2-为什么是Observables?
- Android Rxjava和retrofit
- android Rxjava+Retrofit
- Android MVP +Retrofit+RxJava
- Android OkHttp Retrofit RxJava
- Rxjava + Retrofit 通俗易懂入门实例
- Retrofit+RxJava实战日志(2)-基本使用
- Android Retrofit RxJava实现缓存
- Android Mvp+Rxjava+Retrofit实战
- Android Mvp+RxJava+Retrofit 实战
- Android RxJava+Retrofit完美封装
- RxJava+Retrofit的Android开发
- Android Retrofit + RxJava使用详解
- Android RxJava Retrofit上传图片
- Android RxJava+Retrofit完美封装
- WCF入门教程(三)定义服务协定--属性标签
- 基于子公司与总公司同步数据问题
- 另一位与西蒙斯齐名的福布斯金融大鳄——肯尼斯·格里芬
- unity手游性能优化随手记
- 见站 建好站 自助建站 一键操作
- Android Retrofit 2,RxJava 2精要实例
- 由于控制器不销毁且使用了通知而造成重复多次执行通知的事件
- WCF入门教程(四)通过Host代码方式来承载服务
- NavigationView的使用
- Severalports (8005, 8080, 8009) required by MyEclipseTomcat v7.0 are already in use.
- 理解ThreadLocal(线程局部变量)
- redis集群搭建
- 连续组数组的最大和
- flex TitleGroup组件 遍历子项