美文网首页
MVP+Rxjava+Retrofit

MVP+Rxjava+Retrofit

作者: hongzhenw | 来源:发表于2017-09-26 12:40 被阅读0次

前言

简单的示例DEMO,小记一下

RetrofitUtil.java

/**
 * Created by kevin on 9/25/17.
 */
public class RetrofitUtil {

    //超时时间
    private final static long TIME_OUT = 700;
    //请求URL地址
    private final static String mUrl = "https://api.douban.com/v2/";

    /**
     * 静态内部类单例
     */
    private RetrofitUtil() {
    }

    public static RetrofitUtil getInstance() {
        return RetrofitUtilHolder.instance;
    }

    static class RetrofitUtilHolder {
        private static final RetrofitUtil instance = new RetrofitUtil();
    }

    /**
     * 实例化Retrofit
     *
     * @return Retrofit
     */
    private static Retrofit getRetrofit(String url) {

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .writeTimeout(TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();

        return retrofit;
    }

    /**
     * Book实体类
     *
     * @return BookAPI
     */
    public BookAPI getBookFromServer() {
        return getRetrofit(mUrl).create(BookAPI.class);
    }
}

BookAPI.java

/**
 * 两种入参方式
 *
 * Created by kevin on 9/25/17.
 */
public interface BookAPI {

    @GET("book/search")
    Observable<BookEntity> getBookAPI(@Query("q") String name, @Query("tag") String tag, @Query("start") int start, @Query("count") int count);

    @POST("book/search")
    Observable<BookEntity> getBookApiByBody(@Body BookIn bookIn);
}

BookPresenter.java

public class BookPresenter implements Presenter {

    private BookControl mControl;
    private BookView mBookView;
    private CompositeSubscription mSubscription;
    private BookEntity mBook;
    private CustomDialog mDialog;

    @Override
    public void onCreate() {
        mControl = new BookControl();
        mSubscription = new CompositeSubscription();

    }

    @Override
    public void onStop() {
        if (mSubscription.hasSubscriptions()) {
            mSubscription.unsubscribe();
        }
    }

    @Override
    public void onAttachView(BaseView view) {
        mBookView = (BookView) view;
    }

    /**
     * 弹出Dialog
     *
     * @param activity
     */
    public void showDialog(Activity activity) {
        if (null == mDialog) {
            mDialog = new CustomDialog(activity, R.style.CustomDialog);
        }
        mDialog.show();
    }

    /**
     * 取消Dialog
     */
    public void disDialog() {
        if (null != mDialog) {
            mDialog.dismiss();
        }
    }

    /**
     * 获取书本信息
     *
     * @param activity
     * @param name
     * @param tag
     * @param start
     * @param count
     */
    public void getBookAPI(final Activity activity, String name, String tag, int start, int count) {
        mSubscription.add(mControl.getBookAPI(name, tag, start, count)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        showDialog(activity);
                    }
                }).doAfterTerminate(new Action0() {
                    @Override
                    public void call() {
                        disDialog();
                    }
                })
                .subscribe(new Observer<BookEntity>() {
                    @Override
                    public void onCompleted() {
                        if (null != mBook) {
                            mBookView.onSuccess(mBook);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        mBookView.onFailed("请求失败!");
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(BookEntity book) {
                        mBook = book;
                    }
                }));
    }

    public void getBookApiByBody(final Activity activity, BookIn bookIn) {
        mSubscription.add(mControl.getBookApiByBody(bookIn)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        showDialog(activity);
                    }
                }).doAfterTerminate(new Action0() {
                    @Override
                    public void call() {
                        disDialog();
                    }
                }).subscribe(new Observer<BookEntity>() {
                    @Override
                    public void onCompleted() {
                        if (null != mBook) {
                            mBookView.onSuccess(mBook);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        mBookView.onFailed("请求失败!");
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(BookEntity book) {
                        mBook = book;
                    }
                }));
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private TextView mResult;
    private BookPresenter mBookPresenter = new BookPresenter();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initData();
        initEvent();
    }

    /**
     * 初始化事件监听
     */
    private void initEvent() {
        mBookPresenter.onAttachView(new BookView() {
            @Override
            public void onSuccess(BookEntity book) {
                mResult.setText(book.toString());
            }

            @Override
            public void onFailed(String failed) {
                Toast.makeText(MainActivity.this, failed, Toast.LENGTH_SHORT).show();
            }
        });
    }


    /**
     * 点击事件
     *
     * @param view
     */
    public void click1(View view) {
        mBookPresenter.getBookAPI(this, "西游记", null, 0, 1);
    }

    /**
     * 点击事件
     *
     * @param view
     */
    public void click2(View view) {
        BookIn bookIn = new BookIn();
        bookIn.setQ("西游记");
        bookIn.setTag(null);
        bookIn.setStart(0);
        bookIn.setCount(1);
        mBookPresenter.getBookApiByBody(this, bookIn);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        mBookPresenter.onCreate();
    }

    /**
     * 初始化View
     */
    private void initView() {
        mResult = (TextView) findViewById(R.id.tv_result);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mBookPresenter.onStop();
    }
}

运行截图

device-2017-09-26-124008.png

下载地址:Github

相关文章

网友评论

      本文标题:MVP+Rxjava+Retrofit

      本文链接:https://www.haomeiwen.com/subject/hvdsextx.html