RxAndroid的初体验

从去年开始开始接触RxJava,但项目中期使用的话整体修改较大,目前项目都告一段落,有时间来研究下,既然用我们就用最新的版本。

1、app dependencies

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'io.reactivex:rxandroid:1.1.0'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.0.1'
    compile 'com.squareup.retrofit2:converter-gson:2.0.1'
    compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'
    compile 'com.jakewharton.rxbinding:rxbinding:0.4.0'
}

2、Api接口,定义项目中用到的接口

import io.edgarcode.jiaxibao_retrofit.model.User;
import io.edgarcode.jiaxibao_retrofit.model.Task;
import retrofit2.http.GET;
import retrofit2.http.Query;
import rx.Observable;

/**
 * Created by zhangjifeng on 16/4/11.
 */
public interface Api {

    @GET("user/login.json")
    Observable<User> login(
            @Query("username") String username,
            @Query("password") String password,
            @Query("deviceId") String deviceId,
            @Query("role") int role
    );

    @GET("task/list.json")
    Observable<Task> getTaskList (
            @Query("token") String token,
            @Query("state") int taskState,
            @Query("pageNo") int pageNo,
            @Query("pageSize") int pageSize
    );

}

3、定义Retrofit的相关操作,包含设置Retrofit的http处理层,设置log的等级,设置转换工厂

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;

import com.jakewharton.rxbinding.view.RxView;

import java.util.concurrent.TimeUnit;

import io.edgarcode.jiaxibao_retrofit.model.Task;
import io.edgarcode.jiaxibao_retrofit.model.User;
import io.edgarcode.jiaxibao_retrofit.net.RetrofitInstance;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity{

    private static final String TAG = "MainActivity";

    private TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.tv);
        //RxBind click事件
        RxView.clicks(findViewById(R.id.btn_login))
                .throttleFirst(1, TimeUnit.SECONDS) //防止手快的点击
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        login();
                    }
                });
    }

    private void login() {
        RetrofitInstance.getApi().login("186xxxxxxxx", "123456", "123", 0)
                //转换,user->string(token)
                .map(new Func1<User, String>() {
                    @Override
                    public String call(User user) {
                        return user.getData().getToken();
                    }
                })
                //转换,token->返回Observable<Task>
                .flatMap(new Func1<String, Observable<Task>>() {
                    @Override
                    public Observable<Task> call(String token) {
                        return RetrofitInstance.getApi().getTaskList(token, 1, 1, 10);
                    }
                })
                //转换,将List<Task.TaskBean> 展开,返回Observable<Task.TaskBean>
                .flatMap(new Func1<Task, Observable<Task.TaskBean>>() {
                    @Override
                    public Observable<Task.TaskBean> call(Task task) {
                        return Observable.from(task.getData());
                    }
                })
                .subscribeOn(Schedulers.io()) //在异步线程中处理
                .observeOn(AndroidSchedulers.mainThread()) //订阅后结果在主线程
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        Log.i(TAG, "showLoading...");
                    }
                })
                .doAfterTerminate(new Action0() {
                    @Override
                    public void call() {
                        Log.i(TAG, "hideLoading...");
                    }
                })
                .subscribe(new Subscriber<Task.TaskBean>() {
                    @Override
                    public void onCompleted() {
                        Log.i(TAG ,"onCompleted");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i(TAG, "onError", e);
                    }

                    @Override
                    public void onNext(Task.TaskBean bean) {
                        Log.i(TAG,"onNext bean = " + bean.getTitle());
                    }
                });

    }

}


发布了36 篇原创文章 · 获赞 15 · 访问量 16万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览