MVP+Retrofit+RxJava 使用

来源:互联网 发布:双十一淘宝口令红包 编辑:程序博客网 时间:2024/05/16 12:32

用了这么久的MVP,今天也在此记录一下,好好学习,天天向上!!!感觉也没啥说的,看代码吧......

1、添加依赖

/*网络请求*/    compile 'com.squareup.okio:okio:1.8.0'    compile 'com.squareup.okhttp3:okhttp:3.2.0'    compile 'com.google.code.gson:gson:2.2.4'    compile 'com.squareup.retrofit2:retrofit:2.1.0'    compile 'com.squareup.retrofit2:converter-gson:2.1.0'    compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'    compile 'io.reactivex:rxandroid:1.2.0'    compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'

2、Retrofit网络框架封装,支持RxJava

public class RetrofitUtils {    private Retrofit retrofit;    private RetrofitApiService retrofitApiService;    public RetrofitUtils() {        //   日志拦截器        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {            @Override            public void log(String message) {                try {                    String text = URLDecoder.decode(message, "utf-8");                    LogT.i("OKHttp-----", text);                } catch (UnsupportedEncodingException e) {                    e.printStackTrace();                    LogT.i("OKHttp-----", message);                }            }        });        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);        File cacheFile = new File(MaterialApplication.context.getCacheDir(), "cache");        Cache cache = new Cache(cacheFile, 1024 * 1024 * 100); //100Mb        //设置超时时间、拦截、缓存(no)        OkHttpClient client = new OkHttpClient.Builder()                .connectTimeout(15, TimeUnit.SECONDS)                .readTimeout(15, TimeUnit.SECONDS)                .writeTimeout(15, TimeUnit.SECONDS)                .addInterceptor(interceptor)                .cache(cache)                .build();        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").serializeNulls().create();        if (retrofit == null) {            retrofit = new Retrofit.Builder()                    .baseUrl(RetrofitApiService.BASE_URL)                    .client(client)                    .addConverterFactory(GsonConverterFactory.create(gson))                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//支持RxJava                    .build();        }        retrofitApiService = retrofit.create(RetrofitApiService.class);    }    //  创建单例    private static class SingletonHolder {        private static final RetrofitUtils INSTANCE = new RetrofitUtils();    }    public static RetrofitApiService getApiService() {        return SingletonHolder.INSTANCE.retrofitApiService;    }}
----------------------------------------------------------------------------

public interface RetrofitApiService {    public static final String BASE_URL = "https://api.douban.com/v2/";//网络请求地址    @GET("book/search")    Observable<BookBean> getSearchBook(@Query("q") String name, @Query("tag") String tag, @Query("start") int start, @Query("count") int count);}
-----------------------------------------------------------------------------

再来一个管理类,管理我们的网络请求:

public class DataManager {    private static final DataManager ourInstance = new DataManager();    private RetrofitApiService mRetrofitApiService;    public static DataManager getInstance() {        return ourInstance;    }    private DataManager() {        this.mRetrofitApiService = RetrofitUtils.getApiService();    }    public Observable<BookBean> getSearchBooks(String name, String tag, int start, int count){        return mRetrofitApiService.getSearchBook(name,tag,start,count);    }}

3、MVP相关操作

a、抽取BasePresenter:

public class BasePresenter<V> {    public BaseActivty mContext;    public BasePresenter(BaseActivty context) {        mContext = context;    }    protected Reference<V> mViewRef;    public void attachView(V view) {        mViewRef = new WeakReference<V>(view);    }    public void detachView() {        if (mViewRef != null) {            mViewRef.clear();            mViewRef = null;        }    }    public V getView() {        return mViewRef != null ? mViewRef.get() : null;    }}

b、抽取BaseActivity,BaseFragment做同样的操作在onCreate方法中判断是否使用MVP模式:

public abstract class BaseActivty<V, T extends BasePresenter<V>> extends AppCompatActivity {    protected T mPresenter;    @Override    protected void onCreate(@Nullable Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        //判断是否使用MVP模式        mPresenter = createPresenter();        if (mPresenter != null) {            mPresenter.attachView((V) this);//因为之后所有的子类都要实现对应的View接口        }    }    //用于创建Presenter和判断是否使用MVP模式(由子类实现)    protected abstract T createPresenter();    @Override    protected void onDestroy() {        super.onDestroy();        if (mPresenter != null) {            mPresenter.detachView();        }    }}
-----------------------------------------------------------------------------------------------

public abstract class BaseFragment<V, T extends BasePresenter<V>> extends Fragment {    protected T mPresenter;    @Override    public void onCreate(@Nullable Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        //判断是否使用MVP模式        mPresenter = createPresenter();        if (mPresenter != null) {            mPresenter.attachView((V) this);//因为之后所有的子类都要实现对应的View接口        }    }    //用于创建Presenter和判断是否使用MVP模式(由子类实现)    protected abstract T createPresenter();    @Override    public void onDestroy() {        super.onDestroy();        if (mPresenter != null) {            mPresenter.detachView();        }    }    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle            savedInstanceState) {        View view = LayoutInflater.from(container.getContext()).inflate(getLayoutId(), container, false);        initView(view, savedInstanceState);        return view;    }    protected abstract boolean isStatusHave();    //获取布局文件ID    protected abstract int getLayoutId();    protected abstract void initView(View view, Bundle savedInstanceState);}

4、处理具体业务

基本工作已经做完,现在可以开心的进行网络请求,展示数据了。

public class BookFragment extends BaseFragment<BookView, BookPresenter> implements BookView {    @Bind(R.id.tv_name)    TextView mTvName;    @Override    protected BookPresenter createPresenter() {        return new BookPresenter((BaseActivty) getActivity());    }    @Override    protected boolean isStatusHave() {        return true;    }    @Override    protected int getLayoutId() {        return R.layout.fragment_book;    }    @Override    protected void initView(View view, Bundle savedInstanceState) {        ButterKnife.bind(this, view);        mPresenter.getBook("西游记", null, 0, 1);    }    @Override    public void onGetBook(BookBean mBook) {        mTvName.setText(mBook.getBooks().get(0).getAuthor().get(0));    }    @Override    public void onError(String error) {        // TODO: 2017/12/7    }    @Override    public void onDestroyView() {        super.onDestroyView();        ButterKnife.unbind(this);    }}

<?xml version="1.0" encoding="utf-8"?><LinearLayout    android:orientation="vertical"    android:gravity="center"    xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">    <TextView        android:id="@+id/tv_name"        android:layout_width="wrap_content"        android:layout_height="wrap_content"/></LinearLayout>

-------------------------------------------------------------

BookPresenter  和  BookView  :

public class BookPresenter extends BasePresenter<BookView> {    private BookBean mBook;    public BookPresenter(BaseActivty context) {        super(context);    }    public void getBook(String name, String tag, int start, int count) {        Observable<BookBean> searchBook = DataManager.getInstance().getSearchBooks(name, tag, start, count);        searchBook.subscribeOn(Schedulers.io())//请求数据的事件发生在io线程                .observeOn(AndroidSchedulers.mainThread())//请求完成后在主线程更显UI                .subscribe(new Observer<BookBean>() {                    @Override                    public void onCompleted() {                        getView().onGetBook(mBook);                    }                    @Override                    public void onError(Throwable e) {                        getView().onError(e.toString());                    }                    @Override                    public void onNext(BookBean bookBean) {                        mBook = bookBean;                    }                });    }}

public interface BookView {    void onGetBook(BookBean mBook);    void onError(String error);}








原创粉丝点击