美文网首页
★44.Retrofit + Gson + RxJava2

★44.Retrofit + Gson + RxJava2

作者: iDragonfly | 来源:发表于2017-06-29 00:09 被阅读0次

简介

1. 定义Model

public interface Model {
    @GET
    Observable<AResponse> getA(@Body ARequest request);

    @GET
    Observable<BResponse> getB(@Body BRequest request);
}

2. 创建OkHttpClient

OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
        .readTimeout(10, TimeUnit.SECONDS)
        .connectTimeout(9, TimeUnit.SECONDS)
        .build();

3. 构建Gson

Gson gson = new GsonBuilder()
        .setDateFormat("yyyy-MM-dd hh:mm:ss")
        .create();

4. 创建Retrofit

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://www.baidu.com/")
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .build();

5. 创建Model

Model model = retrofit.create(Model.class);

6. 执行网络请求

model.getA(new ARequest())
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Observer<AResponse>() {
            @Override
            public void onSubscribe(Disposable d) { }

            @Override
            public void onNext(AResponse value) { }

            @Override
            public void onError(Throwable e) { }

            @Override
            public void onComplete() { }
        });

相关文章

网友评论

      本文标题:★44.Retrofit + Gson + RxJava2

      本文链接:https://www.haomeiwen.com/subject/oobpcxtx.html