javagwtgwt-rpc

gwt return value when asynchronous callback end


Hello i have got function like that:

    @Override
    public boolean checkExist(String name) {

        final boolean check[] = new boolean[] { false };

        getAllRecordFromServer(new SearchCallback() {

            @Override
            public void onSearchResult(Map<String, Item> itemsMap) {
            //do some action set true when map key equals name  
                 check[0] = true;
            }

            @Override
            public void onSearchError(XMLPacket error) {
                // TODO Auto-generated method stub

            }
        });

        return check[0];
    }

I`am looking for solution and found some article but i do not know how to do it in gwt :/ This code do not working properly ... as you know this is asynchronous callback.

How can i fix this problem i must return value after callback ends.


Solution

  • This code is not working properly ...
    

    The reason is that Your code is in synchronous model and you are making Asynchronous calls.

    I am assuming that you are doing something after you got some result in onSearchResult.

    So,stop executing your code until you got the response from server, Why because you dont know that the callmay fail sometime.

    If you really want to use the value globally ,then

    public boolean returnVal=false;
    
    public void checkExist(String name, MyCallback callback) {
           getAllRecordFromServer(new SearchCallback() {
                @Override
                public void onSearchResult(Map<String, Item> itemsMap) {
                      returnVal=true;
                      proceedFurther(itemsMap) //your next lines of code in this method.
                }
    
                @Override
                public void onSearchError(XMLPacket error) {
                 stopProceedFurther(); //show  some error message to user.
                }
            });