知识树杂谈(2)
一、RxJava理论学习
a. 参考文章
http://gank.io/post/560e15be2dca930e00da1083#toc_28
http://gank.io/post/560e15be2dca930e00da1083
b. 含义
a library for composing asynchronous and event-based programs by using observable sequences. 一个在Java VM上使用可观测的序列来组成异步的、基于事件的程序的库。
特性: 扩展的观察者模式、异步(线程控制)、变换(类型转换)。
c. 简单例子
通过一个url加载一张图,恩为了演示RxJava和线程控制,我用HttpUrlConnection来做一个实例。
Observable.create(new Observable.OnSubscribe<Bitmap>() { @Override public void call(Subscriber<? super Bitmap> subscriber) { try { URL url = new URL("http://img4.imgtn.bdimg.com/it/u=815679381,647288773&fm=21&gp=0.jpg"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); InputStream in = connection.getInputStream(); Bitmap bitmap = BitmapFactory.decodeStream(in); subscriber.onNext(bitmap); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }) .observeOn(AndroidSchedulers.mainThread()) //指定subscriber的回调发生在UI线程 .subscribeOn(Schedulers.newThread()) //指定subscribe()发生在新线程 .subscribe(new Subscriber<Bitmap>() { @Override public void onCompleted() { plan.setVisibility(View.GONE); } @Override public void onError(Throwable e) { e.printStackTrace(); } @Override public void onNext(Bitmap bitmap) { if (bitmap != null) { image.setImageBitmap(bitmap); onCompleted(); } } }); }
齊帥