Retrofit与Rxjava结合使用实例

环境配置

在Module:app的build.gradle下添加如下依赖,然后sync now。下面这些依赖有些没有用到,暂时都添加进去不会有错。

dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
    implementation 'com.squareup.retrofit2:converter-scalars:2.4.0'
    implementation 'com.squareup.okhttp3:okhttp:3.11.0'
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
    implementation 'io.reactivex.rxjava2:rxjava:2.2.2'
    implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
    implementation 'com.trello.rxlifecycle2:rxlifecycle:2.2.2'
    implementation 'com.trello.rxlifecycle2:rxlifecycle-components:2.2.2'
    implementation 'io.reactivex:rxandroid:1.2.1'
}

具体框架搭建

以下是我的项目目录的网络连接部分,使用了mvp模式。

首先根据retrofit的注释方法建立一个接口,参数是url中要传入的数据。

public interface RetrofitService {
    @GET("bubbleWeb/user?method=regist")
    Observable<User> regist(
            @Query("nickname")String nickname,
            @Query("password")String password
    );
}

接下来将写一个单例模式将retrofit封装起来。

.baseUrl("http://")这里填自己的ip地址。

public class WebService {
    private  static  final String TAG = "WebService";
    private Context mContext;
    OkHttpClient client = new OkHttpClient();
    GsonConverterFactory factory = GsonConverterFactory.create(new GsonBuilder().create());
    private static WebService instance = null;
    private Retrofit mRetrofit = null;
    public static WebService getInstance(){
        if (instance == null){
            instance = new WebService();
        }
        return instance;
    }
    private WebService(){
        this.mContext = Utils.getContext();
        init();
    }

    private void init() {
        resetApp();
    }

    private void resetApp() {
        mRetrofit = new Retrofit.Builder()
                .baseUrl("http://***.***.***.***/")
                .client(client)
                .addConverterFactory(factory)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
    }
    public RetrofitService getServer(){
        return mRetrofit.create(RetrofitService.class);
    }

}

model层:

public class UserManager {
    private RetrofitService service;

    public UserManager() {
        this.service=WebService.getInstance().getServer();
    }

    public Observable<User> regist(String nickname, String password){
        return service.regist(nickname, password);
    }
}

View层:

public interface View {
}

public interface UserView extends View {
    void onSuccess(User user);
    void onError(String result);
}

Present层:

接口

public interface Presenter {
    void onCreate();

    void onStart();

    void onStop();

    void pause();

    void attachView(View view);

    void attachIncomingIntent(Intent intent);
}
public class UserPresenter implements Presenter {
    private UserManager manager;
    private CompositeSubscription subscription;
    private UserView view;
    private User mUser;
    private Observer<User> userObserver  = new  Observer<User>() {
        @Override
        public void onCompleted() {
            if(mUser!=null){
                view.onSuccess(mUser);
            }

        }
        @Override
        public void onError(Throwable e) {
            e.printStackTrace();
            view.onError("请求失败!");
        }
        @Override
        public void onNext(User user) {
            mUser = user;
        }
    };
    @Override
    public void onCreate() {
        manager = new UserManager();
        subscription = new CompositeSubscription();
    }
    @Override
    public void onStart() {

    }
    @Override
    public void onStop() {
        if(subscription.hasSubscriptions()){
            //停止订阅,防止内存泄漏
            subscription.unsubscribe();
        }
    }
    @Override
    public void pause() {
    }
    @Override
    public void attachView(View view) {
        this.view =(UserView) view;
    }
    @Override
    public void attachIncomingIntent(Intent intent) {
    }
    public void regist(String nickname, String password){
        subscription.add(manager.regist(nickname, password)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(userObserver)
        );
    }
}

实例化调用

1.实现View接口的onSuccess和onError方法,可以在方法中操作ui

2.Present要在Activity的生命周期完结时一起回收。

private UserPresenter presenter = new UserPresenter();
...
presenter.regist(nickname,password);
...
private UserView userView= new UserView() {
    @Override
    public void onSuccess(User user) {
        finish();
        Intent intent = new Intent(getApplicationContext(), FriendsListActivity.class);
        startActivity(intent);
    }

    @Override
    public void onError(String result) {
        Toast.makeText(getApplicationContext(),result, Toast.LENGTH_SHORT).show();
    }
};
...
@Override
protected void onDestroy(){
    super.onDestroy();
    presenter.onStop();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值