Nonblocking I/O operations

Now that we know how to schedule a task on an I/O-specific Scheduler, we can modify our storeBitmap() function and check the StrictMode violation again. For the sake of our example, we can rearrange the code in a new blockingStoreBitmap() function:

private static void blockingStoreBitmap(Context context,  Bitmap bitmap, String filename) {
    FileOutputStream fOut = null;
try {
        fOut = context.openFileOutput(filename,  Context.MODE_PRIVATE);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        fOut.flush();
        fOut.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
try {
if (fOut != null) {
    fOut.close();
    }
} catch (IOException e) {
    throw new RuntimeException(e);
  }
 }
}

Now, we create our nonblocking version using Schedulers.io():

public static void storeBitmap(Context context, Bitmap  bitmap, String filename) {
    Schedulers.io().createWorker().schedule(() -> {
blockingStoreBitmap(context, bitmap, filename);
    });
}

Every time we call storeBitmap(), RxJava takes care of creating all it needs to execute our task on a specific I/O thread from the I/O thread pool. All the operations are performed away from the UI thread and our app is 1 second faster than before: no more StrictMode violations in the logcat.

The following figure shows the two different approaches we saw in the storeBitmap() scenario:

Nonblocking I/O operations
..................Content has been hidden....................

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