package com.example.demorxjava;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class SchedulersActivity extends AppCompatActivity {
private Observable<String> mObservable;
private Subscriber<String> mSubScriber;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//一。可观察对象产生数据
//call当产生订阅关系
//-->只机注册的观察者
//结束
mObservable = Observable.create(new Observable.OnSubscribe<String>() {
//call当产生订阅关系
@Override
public void call(Subscriber<? super String> subscriber) {
try {
Thread.sleep(3000);//io
} catch (InterruptedException e) {
e.printStackTrace();
}
printThread("OnSubscribe-call");
subscriber.onNext("this is message");//-->只机注册的观察者
//int value=1/0;//-->异常事件 交给onError
subscriber.onCompleted();//结束
}
});
//二。观察者 接收数据事件 一定订阅
/*接收完成事件*//*处理出错*//*接收更新数据*/
mSubScriber = new Subscriber<String>() {
/*接收完成事件*/
@Override
public void onCompleted() {
ToastUtil.showShort(getApplicationContext(),"接收完成事件onCompleted");
}
/*处理出错*/
@Override
public void onError(Throwable e) {
ToastUtil.showShort(getApplicationContext(),"接收异常处理e"+e.getMessage());
}
/*接收更新数据*/
@Override
public void onNext(String data) {
printThread("Subscriber-onNext");
ToastUtil.showShort(getApplicationContext(),"接收onNext事件 "+data);
}
};
}
public void start(View view)
{
//subscribeOn()设置可观察对象的调度器
//observeOn设置一个安卓专用的更新界面的主线程调度器
//调度器用来给call分配线程
mObservable.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(mSubScriber);//-->数据改变
}
private void printThread(String method)
{
System.out.println("method:"+method+" curr Thread:"+Thread.currentThread().getName());
}
}