2011-10-11

GWT: Synchronous Code Execution Using Callbacks

   @Override
    public void onModuleLoad() {
        startingHere();
    }

    void startingHere() {
        callback_To_Execute_And_Wait_Until_It_Returns(new Callback<Integer, String>() {
            @Override
            public void onFailure(final String reason) {
                System.out.println("callback failed because: " + reason);
            }

            @Override
            public void onSuccess(final Integer callback_return_value) {
                System.out.println("executed SECOND");
                System.out.println("callback result: " + callback_return_value);
                do_something_that_requires_the_callback_to_finish_successfully();
            }
        });
    }

    void callback_To_Execute_And_Wait_Until_It_Returns(final Callback<Integer, String> cb) {
        System.out.println("executed FIRST");
        do_something_that_has_to_finish_completely_before_the_callback_succeeds();
        final Integer this_might_be_the_return_value_of_the_callback = 42;
        cb.onSuccess(this_might_be_the_return_value_of_the_callback);
        System.out.println("==============");
    }

    void do_something_that_requires_the_callback_to_finish_successfully() {
        // ...
    }

    void do_something_that_has_to_finish_completely_before_the_callback_succeeds() {
        // ...
    }