Retrofit + rxjava 使用案例
配置:
retrofit 到 rxjava 转化库
compile 'io.reactivex:rxandroid:1.9.0'
compile 'io.reactivex:rxjava:1.9.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0'
Retrofit 配置:
Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).client(client) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build();
案例1: 与Retrofit 配合使用
//接口:
@FormUrlEncoded @POST("userv2/login") Observable<Base<User>> login(@Field("mobile") String mobile,@Field("password") String password,@Field("deviceType") String deviceType);
使用:
RestClient.getApiService().login(phone, encryptPassword,"0").subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<Base<User>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Base<User> userBase) { } });
案例2: 搜索框搜索相关列表,自动延迟400ms,
//搜索并回显
mSearchResultsSubject = PublishSubject.create(); mTextWatchSubscription = mSearchResultsSubject .debounce(400, TimeUnit.MILLISECONDS) .observeOn(Schedulers.io()) .map(new Func1<String, List<String>>() { @Override public List<String> call(String s) { return mRestClient.searchForCity(s); } }) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<List<String>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(List<String> cities) { handleSearchResults(cities); } });
// 文本框自动输入 mSearchInput.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { mSearchResultsSubject.onNext(s.toString()); } @Override public void afterTextChanged(Editable s) { } });
案例3:发送验证码后,倒计时功能
final long count = TOTAL_TIME / 1000; Observable.interval(0, 1, TimeUnit.SECONDS)//设置0延迟,每隔一秒发送一条数据 .take((int) (count + 1)) //设置总共发送的次数 .map(new Func1<Long, Long>() { //将数值倒置 @Override public Long call(Long aLong) { return count - aLong; // } }) .subscribeOn(Schedulers.computation()) // doOnSubscribe 执行线程由下游逻辑最近的 subscribeOn() 控制,下游没有 subscribeOn() 则跟Subscriber 在同一线程执行 //执行计时任务前先将 button 设置为不可点击 .doOnSubscribe(new Action0() { @Override public void call() { mStart.setEnabled(false);//在发送数据的时候设置为不能点击 mStart.setBackgroundColor(Color.GRAY);//背景色设为灰色 } }) .observeOn(AndroidSchedulers.mainThread())//操作UI主要在UI线程 .subscribe(new Subscriber<Long>() { @Override public void onCompleted() { mTvValue.setText(getResources().getString(R.string.done)); mStart.setEnabled(true); mStart.setBackgroundColor(Color.parseColor("#f97e7e")); } @Override public void onError(Throwable e) { e.printStackTrace(); } @Override public void onNext(Long aLong) { //接收到一条就是会操作一次UI String value = String.valueOf(aLong); mTvValue.setText(value); } });