RxAndroid 官方demo理解

时间:2022-09-16 17:46:42
package com.rxandroid.test1;

import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Process;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.android.schedulers.HandlerScheduler;
import rx.exceptions.OnErrorThrowable;
import rx.functions.Func0;

public class MainActivity extends AppCompatActivity {
private static final String TAG = "------RxAndroidSamples";

private Handler backgroundHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

//创建子线程handler
BackgroundThread backgroundThread = new BackgroundThread();
backgroundThread.start();
backgroundHandler = new Handler(backgroundThread.getLooper());

findViewById(R.id.button_run_scheduler).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onRunSchedulerExampleButtonClicked();
}
});
}

/**
* 整个流程就如同 取款机:
* 先输入取款数目,(订阅,要钱的需求)
* 然后取款机自动吐出对应数目的钱(观察输入信号)
*/
void onRunSchedulerExampleButtonClicked() {
sampleObservable()
// Run on a background thread
.subscribeOn(HandlerScheduler.from(backgroundHandler))//订阅在子线程
// Be notified on the main thread
.observeOn(AndroidSchedulers.mainThread())//观察在主线程,也就是结果会在主线程中执行
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
Log.d(TAG, "onCompleted()");
Log.d(TAG, "SubscriberThread:" + Thread.currentThread().getName());//Main
}

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

@Override
public void onNext(String string) {//这将会在主线程中执行
Log.d(TAG, "onNext(" + string + ")");
}
});
}

static Observable<String> sampleObservable() {
return Observable.defer(new Func0<Observable<String>>() {//定义一个方法,接口中的方法返回Observable<String>
@Override
public Observable<String> call() {
try {
// Do some long running operation
Thread.sleep(TimeUnit.SECONDS.toMillis(5));//睡眠5s
Log.d(TAG, "ObservableThread:" + Thread.currentThread().getName());
} catch (InterruptedException e) {
throw OnErrorThrowable.from(e);
}
return Observable.just("one", "two", "three", "four", "five");//发布5个字符串,子线程中
}
});
}

/**
* 创建子线程的handler或者说looper
*/
static class BackgroundThread extends HandlerThread {
BackgroundThread() {
super("SchedulerSample-BackgroundThread", Process.THREAD_PRIORITY_BACKGROUND);
}

}
}