循环内的回调:如何知道何时完成?

时间:2016-10-26 14:58:57

标签: android loops callback

在循环中,我需要多次调用带回调的方法。我怎么知道什么时候完成?

@Override
public void onObjectsMustBeParsed(String parsableObjects) {
    String[] parsedObjects = parsableObjects.split(",");

    for (String parsedObject : parsedObjects){

        loadObject(parsedObject, new LoadObjectCallback() {
            @Override
            public void onObjectLoaded(Object object) {
                //Object Loaded
                saveObject(object, new SaveObjectCallback() {
                    @Override
                    public void onObjectSaved() {
                        // Object saved
                    }

                    @Override
                    public void onError() {
                        // Object not saved

                    }
                });
            }

            @Override
            public void onError(Throwable throwable) {
                // Object not Loaded

            }
        });
    }
}


// => do something when all processing of parsed-objects are finished
       // do something if all is ok
       // do other thing if partially ok

注意:为了操纵我的数据,我使用具有本地和远程数据源的存储库。这段代码是存储库的一部分。

2 个答案:

答案 0 :(得分:1)

评论的方法类似,但改为使用AtomicInteger:

 AtomicInteger countDownLatch = null;

   @Override
   public void onObjectsMustBeParsed(String parsableObjects) {
      String[] parsedObjects = parsableObjects.split(",");

      countDownLatch = new AtomicInteger(parsedObjects.length);
      for (String parsedObject : parsedObjects){

         loadObject(parsedObject, new LoadObjectCallback() {
            @Override
            public void onObjectLoaded(Object object) {
               //Object Loaded
               saveObject(object, new SaveObjectCallback() {
                  @Override
                  public void onObjectSaved() {
                     // Object saved
                     int value = countDownLatch.decrementAndGet();
                     if ( value == 0 ) {
                        // we are done
                     }

                  }

                  @Override
                  public void onError() {
                     // Object not saved
                     int value = countDownLatch.decrementAndGet();
                     if ( value == 0 ) {
                        // we are done
                     }
                  }
               });
            }

            @Override
            public void onError(Throwable throwable) {
               // Object not Loaded

            }
         });
      }
   }

答案 1 :(得分:1)

添加一个易失整数,表示正在运行的任务量。启动任务时递增。在onObjectLoaded或onObjectSaved中减少。然后在每次减量后检查任务计数器是否为零。