Avoiding blocking I/O operations

Blocking operations are those operations that force the app to wait for a result before being able to move on to the next operation. Executing a blocking operation on the UI thread will force the UI to freeze, and this will produce a bad user experience.

After we have enabled StrictMode, we start receiving unpleasant messages about how our app is doing badly on disk 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)

The previous message is telling us that our Utils.storeBitmap() function is taking 998 ms to complete: that's 1 second of unnecessary work on our UI thread and 1 second of unnecessary slowness of our app. This is happening because we are accessing the disk in a blocking way. Our storeBitmap() function contains:

FileOutputStream fOut = context.openFileOutput(filename,  Context.MODE_PRIVATE);

This is a direct access to the smartphone's solid memory and it's slow. How can we improve this? The storeBitmap() function saves the installed app icon. It returns void, so there is no reason to wait until it completes before executing the next operation. We could just launch it and let it execute on a different thread. Thread management in Android has changed during the years and this has led to weird app behaviors. We could use AsyncTask, but we saved ourselves from that onPre… onPost… doInBackGround hell a few chapters ago. We are going to do it the RxJava way; long live the Schedulers!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.154.64