Skip to content

ListOperationCallback

Jianghao Lu edited this page Feb 23, 2016 · 1 revision

In Azure SDK for Java, most list or listAll methods, and many other methods that return a long list of items, receives a ListOperationCallback as an argument on their async variant.

For example, the following is the method signature for list virtual machines in a resource group:

// In VirtualMachinesOperations.java
Call<ResponseBody> listAsync(
        final String resourceGroupName,
        final ListOperationCallback<VirtualMachine> serviceCallback);

The user needs to implement an instance of ListOperationCallback that handles the failures and responses.

Usage

A simple user code for this method signature:

vmOps.listAsync("my-rg", new ListOperationCallback<VirtualMachine>() {
    @Override
    public void failure(Throwable t) {
        Logger.log(t.getMessage());
    }

    @Override
    public void success(final ServiceResponse<List<ResourceGroup>> result) {
        updateDisplay(result.getBody());
    }
});

The response in success() callback provides information about the response through an okhttp3.Response object.

On top of this, Azure SDK for Java also provides a progress() callback which can be optionally overridden:

final MainActivity self = this;
vmOps.listAsync("my-rg", new ListOperationCallback<VirtualMachine>() {
    @Override
    public void failure(Throwable t) {
        Logger.log(t.getMessage());
    }

    @Override
    public void success(final ServiceResponse<List<ResourceGroup>> result) {
        updateDisplay(result.getBody());
    }

    @Override
    public PagingBehavior progress(List<ResourceGroup> partial) {
        if (get().size() >= MAX_RESOURCE_GROUPS || self.canceled) {
            updateDisplay(get());
            return PagingBehavior.STOP;
        } else {
            return PagingBehavior.CONTINUE;
        }
    }
});

Users are able to control how many items are fetched max. This is very useful when there are way too many items for a one-time list.

Underlying logic

The way this works is through Azure paging operations. When users call list(), SDK sends an initial request to the REST API. The API will then return an initial list of items with a link to the next page of items. This keeps going on until there is no link in the returned response.

Azure SDK for Java simplifies this process in asynchronous scenarios with a progress() and success() callback.