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
原创粉丝点击