自已封装的 Rx java 一个小工具,方便使用.平时的链式调用代码实在太长,所以简单处理下,使流程简洁清晰,泛型参数只用写一次即可
0遇到的问题
每次使用RxJava时都要这样写,过程十分繁琐,如下
Observable.create(new Observable.OnSubscribe() {
@Override
public void call(Subscriber super String> subscriber) {
//做耗时任务
String result="";
//每次都要写
subscriber.onNext(result);
subscriber.onCompleted();
subscriber.unsubscribe();
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
}
});
前后两个泛型还要保持一致,何不写到一个类里面,写一遍就好了,于是就做了一点小小的改进:
1封装工具
import rx.Observable;
import rx.Scheduler;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* Created by liugd on 2018/4/4.
*
佛祖保佑,永无BUG
*/
public class RxJavaUtils {
/***
* 执行任务(任务线程默认在IO线程,观察线程默认在主线程)
* @param task
* @return
*/
public static Subscriber doTask(RxJavaClass task) {
return doTask(task, Schedulers.io(), AndroidSchedulers.mainThread());
}
/***
*执行任务
* @param task
* @param subscribeThread 任务线程
* @param observeThread 观察者线程
* @return
*/
public static Subscriber doTask(RxJavaClass task, Scheduler subscribeThread, Scheduler observeThread) {
Observable.create(task).subscribeOn(subscribeThread)
.observeOn(observeThread)
.subscribe((Subscriber) task);
return task;
}
public abstract static class RxJavaClass extends Subscriber implements Observable.OnSubscribe {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(T t) {
onTaskCompleted(t);
}
public abstract T onDoTask();
public abstract void onTaskCompleted(T t);
@Override
public final void call(Subscriber super T> subscriber) {
T t = onDoTask();
subscriber.onNext(t);
subscriber.onCompleted();
subscriber.unsubscribe();
}
}
}
2怎么用
(只需传入一个类,重写onDoTask,onTaskCompleted方法即可,onDoTask 默认在io线程执行,onTaskCompleted默认在安卓主线程执行,也可以指定执行的线程,同时泛型T,也只写了一次,保证了onDoTask完成时 返回的参数和onTaskCompleted收到的参数类型一致)
RxJavaUtils.doTask(new RxJavaUtils.RxJavaClass() {
@Override
public String onDoTask() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getId());
return "onDoTask";
}
@Override
public void onTaskCompleted(String s) {
System.out.println(s);
System.out.println(Thread.currentThread().getId());
}
});