知識樹雜談(2)
阿新 • • 發佈:2017-10-05
android using null 一個 .get reat lex let bsp
一、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(); } } }); }
知識樹雜談(2)