非阻塞I/O操作

现在我们知道如何在一个指定I/O调度器上来调度一个任务,我们可以修改storeBitmap()函数并再次检查StrictMode的不合规做法。为了这个例子,我们可以在新的blockingStoreBitmap()函数中重排代码。

  1. private static void blockingStoreBitmap(Context context, Bitmap bitmap, String filename) {
  2. FileOutputStream fOut = null;
  3. try {
  4. fOut = context.openFileOutput(filename, Context.MODE_PRIVATE);
  5. bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
  6. fOut.flush();
  7. fOut.close();
  8. } catch (Exception e) {
  9. throw new RuntimeException(e);
  10. } finally {
  11. try {
  12. if (fOut != null) {
  13. fOut.close();
  14. }
  15. } catch (IOException e) {
  16. throw new RuntimeException(e);
  17. }
  18. }
  19. }

现在我们可以使用Schedulers.io()创建非阻塞的版本:

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

每次我们调用storeBitmap(),RxJava处理创建所有它需要从I / O线程池一个特定的I/ O线程执行我们的任务。所有要执行的操作都避免在UI线程执行并且我们的App比之前要快上1秒:logcat上也不再有StrictMode的不合规做法。

下图展示了我们在storeBitmap()场景看到的两种方法的不同:

非阻塞I/O操作 - 图1