注:本文摘自《RxJava Essentials》翻譯中文版電子書(shū)
StrictMode
StrictMode是一種模式颗管,為了獲得更多出現(xiàn)在代碼中的關(guān)于公共問(wèn)題的信息鹅龄。
StrictMode幫助我們偵測(cè)敏感的活動(dòng)佛纫,如我們無(wú)意的在主線程執(zhí)行磁盤訪問(wèn)或者網(wǎng)絡(luò)調(diào)用囤官。
為了在我們的App中激活StrictMode癣亚,我們只需要在MainActivity中添加幾行代碼寺鸥,即onCreate()方法中這樣:
@Override
public void onCreate() {
super.onCreate();
if (BuildConfig.DEBUG) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());
}
}
我們并不想它總是激活著猪钮,因此我們只在debug構(gòu)建時(shí)使用。這種配置將報(bào)告每一種關(guān)于主線程用法的違規(guī)做法胆建,并且這些做法都可能與內(nèi)存泄露有關(guān):Activities烤低、BroadcastReceivers、Sqlite等對(duì)象笆载。
選擇了penaltyLog()扑馁,當(dāng)違規(guī)做法發(fā)生時(shí),StrictMode將會(huì)在logcat打印一條信息凉驻。
避免阻塞I/O的操作
我們激活StrictMode后檐蚜,我們開(kāi)始收到了關(guān)于我們的App錯(cuò)誤操作磁盤I/O的不良信息。比如:
D/StrictMode StrictMode policy violation; ~duration=998 ms: android.os.StrictMode$StrictModeDiskReadViolation: policy=31 violation=2
at android.os.StrictMode$AndroidBlockGuardPolicy.onReadFromDisk (StrictMode.java:1135)
at libcore.io.BlockGuardOs.open(BlockGuardOs.java:106) at libcore.io.IoBridge.open(IoBridge.java:393)
at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
at android.app.ContextImpl.openFileOutput(ContextImpl.java:918)
at android.content.ContextWrapper.openFileOutput(ContextWrapper. java:185)
at com.packtpub.apps.rxjava_essentials.Utils.storeBitmap (Utils.java:30)
上一條信息告訴我們Utils.storeBitmap()函數(shù)執(zhí)行完耗時(shí)998ms:在UI線程上近1秒的不必要的工作和App上近1秒不必要的遲鈍沿侈。這是因?yàn)槲覀円宰枞姆绞皆L問(wèn)磁盤闯第。
Schedulers
Schedulers 是調(diào)度器。RxJava提供了5種調(diào)度器:
- .io()
- .computation()
- .immediate()
- .newThread()
- .trampoline()
Schedulers.io()
這個(gè)調(diào)度器時(shí)用于I/O操作缀拭。它基于根據(jù)需要咳短,增長(zhǎng)或縮減來(lái)自適應(yīng)的線程池。我們將使用它來(lái)修復(fù)我們之前看到的StrictMode違規(guī)做法蛛淋。由于它專用于I/O操作咙好,所以并不是RxJava的默認(rèn)方法;正確的使用它是由開(kāi)發(fā)者決定的褐荷。
重點(diǎn)需要注意的是線程池是無(wú)限制的勾效,大量的I/O調(diào)度操作將創(chuàng)建許多個(gè)線程并占用內(nèi)存。一如既往的是叛甫,我們需要在性能和簡(jiǎn)捷兩者之間找到一個(gè)有效的平衡點(diǎn)层宫。
Schedulers.computation()
這個(gè)是計(jì)算工作默認(rèn)的調(diào)度器,它與I/O操作無(wú)關(guān)其监。它也是許多RxJava方法的默認(rèn)調(diào)度器:buffer(),debounce(),delay(),interval(),sample(),skip()萌腿。
Schedulers.immediate()
這個(gè)調(diào)度器允許你立即在當(dāng)前線程執(zhí)行你指定的工作厌漂。它是timeout(),timeInterval(),以及timestamp()方法默認(rèn)的調(diào)度器般妙。
Schedulers.newThread()
這個(gè)調(diào)度器正如它所看起來(lái)的那樣:它為指定任務(wù)啟動(dòng)一個(gè)新的線程。
Schedulers.trampoline()
當(dāng)我們想在當(dāng)前線程執(zhí)行一個(gè)任務(wù)時(shí)虑椎,并不是立即涣仿,我們可以用.trampoline()將它入隊(duì)希坚。這個(gè)調(diào)度器將會(huì)處理它的隊(duì)列并且按序運(yùn)行隊(duì)列中每一個(gè)任務(wù)试幽。它是repeat()和retry()方法默認(rèn)的調(diào)度器氏义。
非阻塞I/O操作
假設(shè)blockingStoreBitmap方法是一個(gè)操作IO的方法,會(huì)阻塞線程窗慎,如何用RxJava解決:
public static void storeBitmap(Context context, Bitmap bitmap, String filename) {
Schedulers.io().createWorker().schedule(() -> {
blockingStoreBitmap(context, bitmap, filename);
});
}
每次我們調(diào)用storeBitmap()物喷,RxJava處理創(chuàng)建所有它需要從I / O線程池一個(gè)特定的I/ O線程執(zhí)行我們的任務(wù)。所有要執(zhí)行的操作都避免在UI線程執(zhí)行并且我們的App比之前要快上1秒
SubscribeOn and ObserveOn
RxJava提供了subscribeOn()方法來(lái)用于每個(gè)Observable對(duì)象:
getApps()
.onBackpressureBuffer()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(...);
observeOn()方法將會(huì)在指定的調(diào)度器上返回結(jié)果:如例子中的UI線程捉邢。onBackpressureBuffer()方法將告訴Observable發(fā)射的數(shù)據(jù)如果比觀察者消費(fèi)的數(shù)據(jù)要更快的話脯丝,它必須把它們存儲(chǔ)在緩存中并提供一個(gè)合適的時(shí)間給它們商膊。
執(zhí)行網(wǎng)絡(luò)任務(wù)
作為網(wǎng)絡(luò)訪問(wèn)的第一個(gè)案例伏伐,我們將創(chuàng)建下面這樣一個(gè)場(chǎng)景:
- 加載一個(gè)進(jìn)度條。
- 用一個(gè)按鈕開(kāi)始文件下載晕拆。
- 下載過(guò)程中更新進(jìn)度條藐翎。
- 下載完后開(kāi)始視頻播放。
創(chuàng)建mDownloadProgress实幕,用來(lái)管理進(jìn)度的更新吝镣,它和download函數(shù)協(xié)同工作。
private PublishSubject<Integer> mDownloadProgress = PublishSubject.create();
private Observable<Boolean> obserbableDownload(String source, String destination) {
return Observable.create(subscriber -> {
try {
boolean result = downloadFile(source, destination);
if (result) {
subscriber.onNext(true);
subscriber.onCompleted();
} else {
subscriber.onError(new Throwable("Download failed."));
}
} catch (Exception e) {
subscriber.onError(e);
}
});
}
現(xiàn)在我們需要觸發(fā)下載操作昆庇,點(diǎn)擊下載按鈕:
@OnClick(R.id.button_download)
void download() {
mButton.setText(getString(R.string.downloading));
mButton.setClickable(false);
mDownloadProgress.distinct()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Integer>() {
@Override
public void onCompleted() {
App.L.debug("Completed");
}
@Override
public void onError(Throwable e) {
App.L.error(e.toString());
}
@Override
public void onNext(Integer progress) {
mArcProgress.setProgress(progress);
}
});
String destination = "sdcardsoftboy.avi";
obserbableDownload("http://archive.blender.org/fileadmin/movies/softboy.avi", destination)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(success -> {
resetDownloadButton();
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
File file = new File(destination);
intent.setDataAndType(Uri.fromFile(file),"video/avi");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}, error -> {
Toast.makeText(getActivity(), "Something went south", Toast.LENGTH_SHORT).show();
resetDownloadButton();
});
}
downloadFile:
private boolean downloadFile(String source, String destination) {
boolean result = false;
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(source);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return false;
}
int fileLength = connection.getContentLength();
input = connection.getInputStream();
output = new FileOutputStream(destination);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
if (fileLength > 0) {
int percentage = (int) (total * 100 / fileLength);
mDownloadProgress.onNext(percentage);
}
output.write(data, 0, count);
}
mDownloadProgress.onCompleted();
result = true;
} catch (Exception e) {
mDownloadProgress.onError(e);
} finally {
try {
if (output != null) {
output.close();
}
if (input != null) {
input.close();
}
} catch (IOException e) {
mDownloadProgress.onError(e);
}
if (connection != null) {
connection.disconnect();
mDownloadProgress.onCompleted();
}
}
return result;
}