mvp+retrofit2+rxjava+dagger框架的简单搭建
第一次认真写博客,他们说多写博客技术可以提高,所以我就开始了。
MVP是一个现在比较流行的技术,就是比MVC解耦,然后很绕的那种,类也多,写惯了MVC,在来写MVP有一些那么 不适应,不过日子一长,还是可以的。我个人认为MVP还是要比MVC感觉要好些。
最近比较火的技术rxjava,rxandroid,热修复之类的,weex等,都有去研究,但是研究后感觉不是那么短时间能够吃得下的,入门级可能差不多,后来忙着写功能,出差接项目之类的,感觉之前的研究都白忙活了。所以技术还是要时间来积累的 。我现在对 retrofit+rxjava只是在一个会使用的阶段,深入理解就吃力了,感觉和之前的网络请求的框架比起来也好不到什么啊,可能因为是新技术吧,大家都比较推崇。
代码不是我原生写的,是借鉴别人的,我也是才开始学习,在别人的代码上总结了哈。
有兴趣的,看完了我这篇可以再去学习哈这位大神的点击打开链接
dagger, 一个注入注解的框架,以前我也用过这一类的框架,感觉没有这个那么麻烦。进入正题:
添加依赖:在整个工程下面的build下面添加
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
然后在app 的build下面添加
apply plugin: 'com.neenbedankt.android-apt'
apt 'com.google.dagger:dagger-compiler:2.2'
provided 'org.glassfish:javax.annotation:10.0-b28'
compile 'com.google.dagger:dagger:2.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
compile 'com.squareup.okhttp3:okhttp:3.0.1'
compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'
compile 'io.reactivex:rxandroid:1.2.0'
compile 'io.reactivex:rxjava:1.1.5'
compile 'com.jakewharton.rxbinding:rxbinding:0.4.0'
先来个简单的baseactivity
public abstract class BaseActivity extends AppCompatActivity {
private ProgressDialog progressDialog;
@Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setupActivityComponent();
}
public abstract void setupActivityComponent();
protected void showProgressDialog(String message){
progressDialog=new ProgressDialog(this);
progressDialog.setMessage(message);
progressDialog.show();
}
protected void dissmissProgressDialog(){
if(progressDialog!=null&&progressDialog.isShowing()){
progressDialog.dismiss();
}
}
}
public interface BaseLoadView<T> {
void showLoading();
void hideLoading();
}
再把dagger需要的module和componnent写好:
@Module
public class ApiModule {
@Provides
@Singleton
public OkHttpClient provideOkHttpClient(){
OkHttpClient.Builder builder = new OkHttpClient.Builder();
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
builder.addInterceptor(logging);
}
builder.connectTimeout(60 * 1000, TimeUnit.MILLISECONDS)
.readTimeout(60 * 1000, TimeUnit.MILLISECONDS);
return builder.build();
}
@Provides
@Singleton
public Retrofit provideRestAdapter(OkHttpClient okHttpClient){
Retrofit.Builder builder=new Retrofit.Builder();
builder.client(okHttpClient)
.baseUrl(ApiService.SERVER_URL)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create());
return builder.build();
}
@Provides
@Singleton
public ApiService provideApiService(Retrofit retrofit){
return retrofit.create(ApiService.class);
}
@Provides
@Singleton
public ApiManager provideApiManager(Application application,ApiService apiService){
return new ApiManager(apiService, (MyApp) application);
}
}
@Module
public class AppModule {
private final Application application;
public AppModule(Application application) {
this.application = application;
}
@Provides
@Singleton
public Application provideApplication() {
return application;
}
}
@Singleton
@Component(modules = {AppModule.class,ApiModule.class})
public interface AppComponent {
// LoginComponent plus(LoginModule loginModule);
}
创建自定义application:
public class MyApp extends Application{
public static MyApp get(Context context){
return (MyApp) context.getApplicationContext();
}
private AppComponent appComponent;
@Override
public void onCreate() {
super.onCreate();
appComponent=DaggerAppComponent.builder().appModule(new AppModule(this)).build();
}
public AppComponent getAppComponent(){
return appComponent;
}
}
把返回格式等封装好:
public class BaseResponse<T> {
private int status_code;
private String status_msg;
private T data;
public int getStatus_code() {
return status_code;
}
public void setStatus_code(int status_code) {
this.status_code = status_code;
}
public String getStatus_msg() {
return status_msg;
}
public void setStatus_msg(String status_msg) {
this.status_msg = status_msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
public class BaseResponseFunc<T> implements Func1<BaseResponse<T>, Observable<T>> {
@Override
public Observable<T> call(BaseResponse<T> tBaseResponse) {
//遇到非200错误统一处理,将BaseResponse转换成您想要的对象
if (tBaseResponse.getStatus_code() != 200) {
return Observable.error(new Throwable(tBaseResponse.getStatus_msg()));
}else{
return Observable.just(tBaseResponse.getData());
}
}
}
然后把请求的manager等封装:
public class ApiManager {
private final ApiService apiService;
private final Application application;
public ApiManager(ApiService apiService, Application application) {
this.apiService = apiService;
this.application = application;
}
public void login(String username, String password,SimpleCallback<User> simpleCallback){
apiService.login(username,password)
.flatMap(new BaseResponseFunc<User>())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new ExceptionSubscriber<User>(simpleCallback,application));
}
}
public interface ApiService {
String SERVER_URL="";
@GET("users")
Observable<BaseResponse<User>> login(@Query("username") String username, @Query("password") String password);
}
public class ExceptionSubscriber<T> extends Subscriber<T> {
private SimpleCallback<T> simpleCallback;
private Application application;
public ExceptionSubscriber(SimpleCallback simpleCallback, Application application){
this.simpleCallback = simpleCallback;
this.application = application;
}
@Override
public void onStart() {
super.onStart();
if(simpleCallback != null)
simpleCallback.onStart();
}
@Override
public void onCompleted() {
if(simpleCallback != null)
simpleCallback.onComplete();
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
if (e instanceof SocketTimeoutException) {
Toast.makeText(application, "网络中断,请检查您的网络状态", Toast.LENGTH_SHORT).show();
} else if (e instanceof ConnectException) {
Toast.makeText(application, "网络中断,请检查您的网络状态", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(application, "error:" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
if(simpleCallback != null)
simpleCallback.onComplete();
}
@Override
public void onNext(T t) {
if(simpleCallback != null)
simpleCallback.onNext(t);
}
}
public interface SimpleCallback<T> {
void onStart();
void onNext(T t);
void onComplete();
}
基本上就已经封装好了,先以登录为列:
public class User {
private int id;
private String username;
private String password;
private String gender;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", gender='" + gender + '\'' +
'}';
}
}
下面写登录的依赖注解和mvp的模式代码:
public interface LoginView extends BaseLoadView{
void canLogin(boolean canLogin);
void showUser(User user);
}
@Module
public class LoginModule {
private final LoginView loginView;
public LoginModule(LoginView loginView) {
this.loginView = loginView;
}
@Provides
LoginView provideLoginView() {
return loginView;
}
@Provides
Validator provideValidator(){
return new Validator();
}
@Provides
LoginPresenter provideLoginPresenter(Validator validator, ApiManager apiManager, PreferencesManager preferencesManager) {
return new LoginPresenter(loginView,validator,apiManager,preferencesManager);
}
}
@Subcomponent(modules = LoginModule.class)
public interface LoginComponent {
LoginActivity inject(LoginActivity loginActivity);
}
public class LoginPresenter {
private final LoginView loginView;
private final Validator validator;
private final ApiManager apiManager;
private final PreferencesManager preferencesManager;
public LoginPresenter(LoginView loginView, Validator validator, ApiManager apiManager, PreferencesManager preferencesManager) {
this.loginView = loginView;
this.validator = validator;
this.apiManager = apiManager;
this.preferencesManager = preferencesManager;
}
public void checkInput(String username,String password){
loginView.canLogin(validator.validUsername(username) && validator.validPassword(password));
}
public void login(String username,String password){
apiManager.login(username, password, new SimpleCallback<User>() {
@Override
public void onStart() {
loginView.showLoading();
}
@Override
public void onNext(User user) {
loginView.showUser(user);
}
@Override
public void onComplete() {
loginView.hideLoading();
}
});
}
public void saveLoginInfo(String username,String password){
preferencesManager.saveLoginInfo(username,password);
}
public String getUserNameFromLocal(){
return preferencesManager.getUserName();
}
public String getPasswordFromLocal(){
return preferencesManager.getPassword();
}
}
public class LoginActivity extends BaseActivity implements LoginView{
@Inject
LoginPresenter loginPresenter;
@Bind(R.id.username)
EditText username;
@Bind(R.id.password) EditText password;
@Bind(R.id.login)
Button login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
username.setText(loginPresenter.getUserNameFromLocal());
password.setText(loginPresenter.getPasswordFromLocal());
RxTextView.textChanges(username).subscribe(new Action1<CharSequence>() {
@Override
public void call(CharSequence charSequence) {
loginPresenter.checkInput(charSequence.toString(),password.getText().toString());
}
});
RxTextView.textChanges(password).subscribe(new Action1<CharSequence>() {
@Override
public void call(CharSequence charSequence) {
loginPresenter.checkInput(username.getText().toString(),charSequence.toString());
}
});
}
@OnClick(R.id.login) void onLoginClick() {
loginPresenter.login(username.getText().toString(),password.getText().toString());
}
@Override
public void setupActivityComponent() {
ArchitectureApplication.get(this).getAppComponent().plus(new LoginModule(this)).inject(this);
}
@Override
public void canLogin(boolean canLogin) {
if(canLogin){
login.setEnabled(true);
login.setBackgroundColor(Color.GREEN);
}else{
login.setBackgroundColor(Color.GRAY);
}
}
@Override
public void showUser(User user) {
loginPresenter.saveLoginInfo(user.getUsername(),user.getPassword());
Log.e("showUser",user.toString());
}
@Override
public void showLoading() {
showProgressDialog("加载中...");
}
@Override
public void hideLoading() {
dissmissProgressDialog();
}
}
public class Validator {
public Validator() {
}
public boolean validUsername(String username) {
return !TextUtils.isEmpty(username);
}
public boolean validPassword(String password) {
return !TextUtils.isEmpty(password);
}
}
代码就基本是是那些了。慢慢的理解,多使用几次,就熟悉了。
源码:点击打开链接