你的位置:首页 > 操作系统

[操作系统]mvp+retrofit+rxjava


引用

"retrofit"       : "com.squareup.retrofit2:retrofit:2.0.1",          "retrofit-adapter"   : "com.squareup.retrofit2:adapter-rxjava:2.0.1",          "retrofit-converter"  : "com.squareup.retrofit2:converter-gson:2.0.1",          "gson"         : "com.google.code.gson:gson:2.6.2",          "rxjava"        : "io.reactivex:rxjava:1.1.2",          "rxandroid"       : "io.reactivex:rxandroid:1.1.0",          "okhttp"        : "com.squareup.okhttp3:okhttp:3.2.0",          "okhttp-urlconnection" : "com.squareup.okhttp3:okhttp-urlconnection:3.2.0",          "okhttp-logging"    : "com.squareup.okhttp3:logging-interceptor:3.2.0",          "okhttp-cookie"     : "com.github.franmontiel:PersistentCookieJar:v0.9.3",

View Code

Retrofit

import com.google.gson.Gson;import com.google.gson.GsonBuilder;import java.util.concurrent.TimeUnit;import okhttp3.OkHttpClient;import okhttp3.logging.HttpLoggingInterceptor;import retrofit2.Retrofit;import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;import retrofit2.converter.gson.GsonConverterFactory;/**用于辅助初始化retrofit**/public class RxService {  private static final long DEFAULT_TIMEOUT = 20L;  final static Gson gson = new GsonBuilder()      .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")      .serializeNulls()// 调用serializeNulls方法,改变gson对象的默认行为,null值将被输出      .create();  //addInterceptor:设置应用拦截器,可用于设置公共参数,头信息,日志拦截等  //addNetworkInterceptor:网络拦截器,可以用于重试或重写,对应与1.9中的setRequestInterceptor。  //setLevel NONE(不记录) BASIC(请求/响应行) HEADER(请求/响应行 + 头) BODY(请求/响应行 + 头 + 体)  //cookieJar:保持在同一个会话里面  //TimeUnit.SECONDS秒做单位  private static OkHttpClient okHttpClient = new OkHttpClient.Builder()      .addNetworkInterceptor(new HttpLoggingInterceptor()          .setLevel(HttpLoggingInterceptor.Level.HEADERS))      .addInterceptor(new HttpLoggingInterceptor()          .setLevel(HttpLoggingInterceptor.Level.BODY))      .cookieJar(App.getInstance().getCookieJar())      .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)      .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)      .build();  private static Retrofit retrofit = null;  private RxService() {}//  private final static RxService rxService = new RxService();  public static <T> T createApi(Class<T> clazz,String url) {    retrofit = new Retrofit.Builder()        .baseUrl(url)        .client(okHttpClient)        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())        .addConverterFactory(GsonConverterFactory.create(gson))        .build();    return retrofit.create(clazz);  }  public static <T> T createApi(Class<T> clazz) {    retrofit = new Retrofit.Builder()        .baseUrl(Config.BASE_DEFAULT)        .client(okHttpClient)        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())        .addConverterFactory(GsonConverterFactory.create(gson))        .build();    return retrofit.create(clazz);  }}

View Code
import retrofit2.http.Field;import retrofit2.http.FormUrlEncoded;import retrofit2.http.POST;import rx.Observable;/** * Created by JDD on 2016/4/8. */public interface ILoginService {  @FormUrlEncoded  @POST(LoginSingleService.URL)  Observable<UsersEntity> login(@Field("token") String token, @Field("userName") String userName, @Field("userPassword") String userPassword);}

View Code
/**创建并配置retrofit service**/public class LoginSingleService {  public static final String URL = "login.do";  protected static final Object monitor = new Object();  static ILoginService sJokeSingleton = null;//  public static final int meizhiSize = 10;//  public static final int gankSize = 5;  //测试service  public static ILoginService getLoginSingleton() {    synchronized (monitor) {      if (sJokeSingleton == null) {        sJokeSingleton = RxService.createApi(ILoginService.class);      }      return sJokeSingleton;    }  }}

View Code
Presenter
import android.util.Log;import rx.Observer;import rx.Subscription;import rx.android.schedulers.AndroidSchedulers;import rx.schedulers.Schedulers;public class LoginPresenter implements ILoginPresenter {  public Subscription login(final String username,final String pwd, final CallBack callBack) {    if (username == null || pwd == null || username.equals("") || pwd.equals("")){      callBack.Error(STATUS.NULL_ERROR);      return null;    }    //观察者Subscription    Subscription s = LoginSingleService.getLoginSingleton()//事件源,被观察者Observable        .login("21341234",username,pwd)        .subscribeOn(Schedulers.io())//指定观察者运行的线程        .map(entity -> entity.getData())        .observeOn(AndroidSchedulers.mainThread())//指定订阅者运行的线程        .subscribe(new Observer<UserEntity>() {//订阅subscriber          @Override          public void onCompleted() {            Log.e("onNext","onCompleted");            callBack.End();          }          @Override          public void onError(Throwable e) {            Log.e("onNext","onError "+e.getMessage());            callBack.Error(STATUS.ERROR);          }          @Override          public void onNext(UserEntity entity) {            STATUS status;            if (entity != null) {              status = STATUS.SUCCESS;              Log.e("onNext","hello "+entity.getName());              App.getInstance().setUserEntity(entity);              App.getInstance().setPerson(entity,pwd);            }            else              status = STATUS.ERROR;            callBack.Success(status);          }        });    return s;  }}

View Code

Main

import android.content.Context;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v7.app.AppCompatActivity;import rx.Subscription;import rx.subscriptions.CompositeSubscription;/** * Created by LiuZhen on 2016/5/11. */public abstract class BaseActivity extends AppCompatActivity {  private final static String TAG = "BaseActivity";  private CompositeSubscription mCompositeSubscription;  protected Context context;  @Override  protected void onCreate(@Nullable Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(getLayoutId());    this.context = BaseActivity.this;  }  public CompositeSubscription getCompositeSubscription() {    if (this.mCompositeSubscription == null) {      this.mCompositeSubscription = new CompositeSubscription();    }    return this.mCompositeSubscription;  }  /**使CompositeSubscription持有订阅**/  public void addSubscription(Subscription s) {    if (this.mCompositeSubscription == null) {      this.mCompositeSubscription = new CompositeSubscription();    }    this.mCompositeSubscription.add(s);  }  @Override  protected void onDestroy() {    super.onDestroy();    if (this.mCompositeSubscription != null) {      this.mCompositeSubscription.unsubscribe();//取消所有的订阅    }  }  protected abstract int getLayoutId();}

View Code
import android.os.Bundle;import android.widget.TextView;import org.greenrobot.eventbus.EventBus;import org.greenrobot.eventbus.Subscribe;import org.greenrobot.eventbus.ThreadMode;public class MainActivity extends BaseActivity {  private TextView username;  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    EventBus.getDefault().register(this);    username = (TextView) findViewById(R.id.username);    username.setText(App.getInstance().getPerson().getName()+" hello");  }  @Override  protected int getLayoutId() {    return R.layout.activity_main;  }  @Subscribe(threadMode = ThreadMode.MAIN)  public void onEvent() {    Toasts.showShort("刷新UI",context);  }  @Override  protected void onDestroy() {    super.onDestroy();    EventBus.getDefault().unregister(this);  }}

View Code