在Android中集成RxJava,Retrofit 2和Gson

时间:2016-05-08 05:38:40

标签: android gson rx-java mvp retrofit2

我开始在android中学习mvp。但是坚持了一天这个问题。请帮我。 我想发送用户名,密码登录api。服务器将重新响应json,我将使用gson解析为Userinfo对象。

这是我的班级RibotService

public interface RibotService {

    String ENDPOINT = "https://....";
    String AUTH_HEADER = "Authorization";



    @POST("/login_api.php")
    Observable<Userinfo> signIn(@Body SignInRequest signInRequest);

这是我的改装设置

 /******** Factory class that sets up a new ribot services *******/
    class Factory {

        public static RibotService makeRibotService(Context context) {
            OkHttpClient okHttpClient = new OkHttpClient();
            okHttpClient.interceptors().add(new UnauthorisedInterceptor(context));
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY
                    : HttpLoggingInterceptor.Level.NONE);
            okHttpClient.interceptors().add(logging);

            Gson gson = new GsonBuilder()
                    .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
                    .create();
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(RibotService.ENDPOINT)
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .build();
            return retrofit.create(RibotService.class);
        }

    }

这是DataManager类中的方法

  public Observable<Userinfo> signIn(final String username, final String password) {
        return mRibotService.signIn(new SignInRequest(username,password));
    }

我在演示者中调用此方法

 public void signInWithGoogle(final String username, String password) {
        Timber.i("Starting sign in with account " + username +"password: "+ password);
        mMvpView.showProgress(true);
//        mMvpView.setSignInButtonEnabled(false);
        mSubscription = mDataManager.signIn(username,password)
        .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(new Subscriber<Userinfo>(){
                    @Override
                    public void onCompleted() {
                        Log.d("voz","login on completed");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d("log","login on error" + e.getMessage());
                    }

                    @Override
                    public void onNext(Userinfo userinfo) {
                        Log.d("log","login on next" + userinfo.getUsername());
                    }

                });

    }

但是在onNext方法中返回Userinfo null,虽然我可以在logcat中看到来自改造的服务器响应。

提前感谢!

0 个答案:

没有答案