简体   繁体   中英

How can I loop over Callback functions in Java/JavaScript?

I have a list of books:

List<Book> books = new ArrayList<Book>();

Now I will iterate over this list an call a function myFunction() on each object.

for(Book book: books) {

  book.myFunction();

}

Now, I have a Callback interface which is called when myFunction() finishes:

public interface MyHandler {
  void onDone();
}

So myFunction is something like:

public void myFunction(MyHandler handler) {

   ...
   handler.onDone();

}

How can I iterate over a list of books and call myFunction(MyHandler handler)?

Note that you can only continue after onDone() is called.

The only thing that doesn't fit is your call to myFunction() , which result in a compile error because the MyHandler parameter is missing.

You just have to provide an object that implements MyHandler to your myFunction() method. You can do this via an anonymous class like this:

for(Book book: books) {
    book.myFunction(new MyHandler() {
        void onDone() {
            // put some code you want to execute here
        }
    });
}

Side note: For posterity, in a context where you can use Java 8, you can even use a lambda expression instead of the anonymous class:

for(Book book: books) {
    book.myFunction(() -> { /* insert code for onDone() here */ });
}

Since you've tagged this as GWT i'm going to assume that your myFunction() call is actaully doing something asynchronous, and that is why you can't simply wait for it to return. In this case you could do the following, although it's a bit messy:

final Iterator<Book> iter = books.iterator();
MyHandler handler = new MyHandler() {
    @Override
    public void onDone() {
        if (iter.hasNext()) 
            iter.next().myFunction(this);
    }
};

//
// Start it going
//
if (iter.hasNext()) 
    iter.next().myFunction(handler);

Note that this is now recursive , so if you have a lot of book objects the call stack is going to get quite deep, and this imposes an upper limit on the number of books before you overflow the stack (an upper limit that you can't reliably know , either) This is not such a problem if you're using a GWT service to trigger the callback, since the stack will have unwound due to the network stuff.

I don't mean to second-guess you here, but if you are calling an async gwt service then it's going to result in a lot of calls back and forth over the network. If this is the case then you could consider simply passing a list of Book objects to be processed to the service, instead of sending them one at a time.

To avoid the async calls, create a method on the server that loops thru the books and thus avoiding the rescursive calls. So you could gave just one call processMybooks(Books)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM