andorid jar/庫源碼解析之Bolts

目錄:andorid jar/庫源碼解析 html

Bolts:

  做用:

    用於鏈式執行跨線程代碼,且傳遞數據java

  栗子:

Task.call(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                return true;
            }
        }, Task.UI_THREAD_EXECUTOR);

        Task.callInBackground(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                return false;
            }
        });

        Task.callInBackground(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                return true;
            }
        }).onSuccess(new Continuation<Boolean, Object>() {
            @Override
            public Object then(Task<Boolean> task) throws Exception {
                if (task.getResult()) {
                    return null;
                } else {
                    return new Object();
                }
            }
        }, Task.BACKGROUND_EXECUTOR).continueWith(new Continuation<Object, Object>() {
            @Override
            public Object then(Task<Object> task) throws Exception {
                if (task.getResult() == null) {
                    Toast.makeText(getBaseContext(), "null", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getBaseContext(), "not null", Toast.LENGTH_SHORT).show();
                }

                return null;
            }
        }, Task.UI_THREAD_EXECUTOR);

  源碼解讀:

  在內部經過維護多中 ExecutorService 對象,而且經過串聯的方式進行調用。android

  而且經過維護內部變量在,在指定流程處,就是特定的,值,值經過Task的對象getResult拿到。git

  UIThreadgithub

/**
   * An {@link java.util.concurrent.Executor} that runs tasks on the UI thread.
   */
  private static class UIThreadExecutor implements Executor {
    @Override
    public void execute(Runnable command) {
      new Handler(Looper.getMainLooper()).post(command);
    }
  }

  BackgroundThreadide

private BoltsExecutors() {
    background = !isAndroidRuntime()
        ? java.util.concurrent.Executors.newCachedThreadPool()
        : AndroidExecutors.newCachedThreadPool();
    scheduled = Executors.newSingleThreadScheduledExecutor();
    immediate = new ImmediateExecutor();
  }

  源碼:https://github.com/BoltsFramework/Bolts-Android

  引入:

implementation 'com.parse.bolts:bolts-android:1.2.0'
相關文章
相關標籤/搜索