學習地址 很全面:web
http://blog.csdn.net/meegomeego/article/details/49155989ide
final String[] words = {"Hello", "Hi", "Aloha"}; Observable.from(words).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() { @Override public void onCompleted() { Logger.e("--->onCompleted"); } @Override public void onError(Throwable e) { } @Override public void onNext(String s) { Logger.e("--->onNext=="+s); } }); //map() 方法將參數中的 String 對象轉換成一個 Bitmap 對象後返回(事件對象的直接變換) Observable.just("xx").map(new Func1<String, Bitmap>() { @Override public Bitmap call(String s) { return null; } }).subscribe(new Action1<Bitmap>() { @Override public void call(Bitmap bitmap) { } }); //flatMap 返回Observable 對象 而後進行平鋪下去 ArrayList<PreSenterEntity> lists=new ArrayList<PreSenterEntity>(); for (int i=0;i<10;i++){ Owener owner= new Owener("name"+i,i); lists.add(new PreSenterEntity(i,"name"+i,owner)); } Observable.from(lists).flatMap(new Func1<PreSenterEntity, Observable<Owener>>() { @Override public Observable<Owener> call(PreSenterEntity preSenterEntity) { return Observable.from((Iterable<? extends Owener>) preSenterEntity.owner); } }).subscribe(new Subscriber<Owener>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Owener owener) { Logger.e(owener.id+"xxxx"+owener.login); } });
subscribeOn()
: 指定 subscribe()
所發生的線程,即 Observable.OnSubscribe
被激活時所處的線程。或者叫作事件產生的線程。observeOn()
: 指定 Subscriber
所運行在的線程。或者叫作事件消費的線程。int drawableRes = ...; ImageView imageView = ...; Observable.create(new OnSubscribe<Drawable>() { @Override public void call(Subscriber<? super Drawable> subscriber) { Drawable drawable = getTheme().getDrawable(drawableRes)); subscriber.onNext(drawable); subscriber.onCompleted(); } }) .subscribeOn(Schedulers.io()) // 指定 subscribe() 發生在 IO 線程 .observeOn(AndroidSchedulers.mainThread()) // 指定 Subscriber 的回調發生在主線程 .subscribe(new Observer<Drawable>() { @Override public void onNext(Drawable drawable) { imageView.setImageDrawable(drawable); } @Override public void onCompleted() { } @Override public void onError(Throwable e) { Toast.makeText(activity, "Error!", Toast.LENGTH_SHORT).show(); } });
建立Observable學習
Observable.create(new Observable.OnSubscribe<Drawable>() { @Override public void call(Subscriber<? super Drawable> subscriber) { Drawable drawable=null; subscriber.onNext(drawable); subscriber.onCompleted(); } }).subscribe(new Observer<Drawable>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Drawable drawable) { } });