Batch requests

Batch requests

It is common to request multiple types of data for a single view within your project. While you can perform each endpoint request separately using multiple object loaders, it is often more efficient to do one single request. The Android SDK contains the BatchBuilder object to make this easier. The BatchBuilder provides an easy-to-use interface to the Xweather Weather API's batch endpoint by combining multiple object loaders and their various options into a single HTTP request.

Before we can use the batch loader, we need to instantiate our Xweather Engine and PlaceParameter objects just as we did in the loading data section. If you haven't read the loading data section which covers making a simple single endpoint request, you should do that now.

Once we have our AerisEngine and PlaceParameter objects, we can set up our BatchBuilder object.

//create the batch builder object
BatchBuilder builder = new BatchBuilder();
 
//set the place
builder.addGlobalParameter(place);

To use the batch loader, you first need to create the instances of the individual object loaders you wish to request data for:

//add an endpoint to the batch request
builder.addEndpoint(new Endpoint(EndpointType.OBSERVATIONS, Action.CLOSEST)
        .addParameters(FieldsParameter.initWith("ob")));
 
//add another endpoint to the batch request
builder.addEndpoint(new Endpoint(EndpointType.PLACES, Action.CLOSEST)
        .addParameters(FieldsParameter.initWith("place")));
 
//add another endpoint to the batch request
builder.addEndpoint(new Endpoint(EndpointType.FORECASTS, Action.CLOSEST)
        .addParameters(new FilterParameter("daynight"),
                new PLimitParameter(2)));
 
//add another endpoint to the batch request
builder.addEndpoint(new Endpoint(EndpointType.FORECASTS, Action.CLOSEST)
        .addParameters(new FilterParameter("3hr"), new PLimitParameter(
                8), FieldsParameter.initWith(ForecastsFields.TEMP_F,
                ForecastsFields.TEMP_C, ForecastsFields.ICON,
                ForecastsFields.DATETIME_ISO, Fields.INTERVAL)));

Now we can compile the batch request object, and make the API call.

//compile the batch request(s)
AerisRequest request = builder.build();
 
BatchCommunicationTask batchTask = new BatchCommunicationTask(this,
        new BatchCallback() {
            @Override
            public void onBatchResponse(AerisBatchResponse aerisBatchResponse) {
                //do something with the data
            }
        }, request);
 
if (listener != null) {
        batchTask.withProgress(listener);
}
 
batchTask.execute();