observeOn(AndroidSchedulers.mainThread())源码分析
AndroidSchedulers.mainThread()源码分析
public static Scheduler mainThread() {
return RxAndroidPlugins.onMainThreadScheduler(MAIN_THREAD);
}
MAIN_THREAD最终实际是这行代码
//new Handler(Looper.getMainLooper())新建了一个Handler ,实际是创建一个Scheduler
static final Scheduler DEFAULT = new HandlerScheduler(new Handler(Looper.getMainLooper()));
observeOn源码分析
public final Observable<T> observeOn(Scheduler scheduler) {
return observeOn(scheduler, false, bufferSize());
}
//实际调用的是ObservableObserveOn
return RxJavaPlugins.onAssembly(new ObservableObserveOn<T>(this, scheduler, delayError, bufferSize));
ObservableObserveOn源码分析
@Override
protected void subscribeActual(Observer<? super T> observer) {
if (scheduler instanceof TrampolineScheduler) {
source.subscribe(observer);
} else {
//创建一个Worker HandlerWorker
Scheduler.Worker w = scheduler.createWorker();
//source上游 ObserveOnObserver下游看这个的onNext
source.subscribe(new ObserveOnObserver<T>(observer, w, delayError, bufferSize));
}
}
ObserveOnObserver的onNext方法
schedule();
void schedule() {
if (getAndIncrement() == 0) {
worker.schedule(this);
}
}
实际调用的是HandlerScheduler中的schedule方法
public Disposable schedule(Runnable run, long delay, TimeUnit unit) {
if (run == null) throw new NullPointerException("run == null");
if (unit == null) throw new NullPointerException("unit == null");
if (disposed) {
return Disposables.disposed();
}
run = RxJavaPlugins.onSchedule(run);
//将run和handler进行封装
ScheduledRunnable scheduled = new ScheduledRunnable(handler, run);
// message。callback!=null
Message message = Message.obtain(handler, scheduled);
message.obj = this; // Used as token for batch disposal of this worker's runnables.
//这个方法执行后会执行run方法
handler.sendMessageDelayed(message, Math.max(0L, unit.toMillis(delay)))
return scheduled;
}
手写主线程切换
使用
Observable.just("http://d.paper.i4.cn/max/2016/10/10/15/1476085552237_716159.jpg")
.map(new Function<String, Bitmap>() {
@Override
public Bitmap apply(@NonNull String s) throws Exception {
URL url = new URL("http://d.paper.i4.cn/max/2016/10/10/15/1476085552237_716159.jpg");
HttpURLConnection httpsURLConnection = (HttpURLConnection) url.openConnection();
httpsURLConnection.connect();
InputStream inputStream = httpsURLConnection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
Log.e("TAG", Thread.currentThread().getName());
return bitmap;
}
}).map(new Function<Bitmap, Bitmap>() {
@Override
public Bitmap apply(@NonNull Bitmap bitmap) throws Exception {
bitmap = createWatermark(bitmap, "rxjava");
Log.e("TAG", Thread.currentThread().getName());
return bitmap;
}
}).subscribeOn(Schedulers.io())
.observeOn(Schedulers.mainThread())
.subscribe(new Consumer<Bitmap>() {
@Override
public void onNext(Bitmap bitmap) {
mImage.setImageBitmap(bitmap);
Log.e("TAG", Thread.currentThread().getName());
}
});
observable中新增方法
public Observable<T> observeOn(Schedulers schedulers) {
return onAssembly(new ObserverOnObservable(this,schedulers));
}
ObserverOnObservable类
public class ObserverOnObservable<T> extends Observable<T> {
final Observable<T> source;
final Schedulers schedulers;
public ObserverOnObservable(Observable<T> source, Schedulers schedulers) {
this.source = source;
this.schedulers = schedulers;
}
@Override
protected void subscribeActual(Observer<? super T> observer) {
source.subscribe(new ObserverOnObserver(observer, schedulers));
}
private class ObserverOnObserver<T> implements Observer< T>, Runnable {
final Observer<T> observer;
final Schedulers schedulers;
T value;
public ObserverOnObserver(Observer<T> observer, Schedulers schedulers) {
this.observer = observer;
this.schedulers = schedulers;
}
@Override
public void onSubscribe() {
observer.onSubscribe();
}
@Override
public void onError(@NonNull Throwable e) {
observer.onError(e);
}
@Override
public void onComplete() {
observer.onComplete();
}
@Override
public void onNext(@NonNull T s) {
this.value = s;
schedulers.scheduleDirect(this);
}
@Override
public void run() {
observer.onNext(value);
}
}
}
修改Schedulers类
public abstract class Schedulers {
static Schedulers MAIN_THREAD;
static Schedulers IO;
static {
IO = new IOSchedulers();
MAIN_THREAD=new MainSchedulers(new Handler(Looper.getMainLooper()));
}
public static Schedulers io() {
return IO;
}
public abstract void scheduleDirect(Runnable runnable);
public static Schedulers mainThread() {
return MAIN_THREAD;
}
private static class IOSchedulers extends Schedulers {
ExecutorService service;
public IOSchedulers() {
service = Executors.newScheduledThreadPool(1, new ThreadFactory() {
@Override
public Thread newThread(@NonNull Runnable r) {
return new Thread(r, "IOSchedulers");
}
});
}
@Override
public void scheduleDirect(Runnable runnable) {
service.execute(runnable);
}
}
private static class MainSchedulers extends Schedulers {
private final Handler handler;
public MainSchedulers(Handler handler) {
this.handler=handler;
}
@Override
public void scheduleDirect(Runnable runnable) {
Message message = Message.obtain(handler,runnable);
handler.sendMessage(message);
}
}
}