alexbirkett
alexbirkett

Reputation: 2682

Run Bolts Task on background executor

I've written a Bolts task implementation to fetch a url:

public class UrlFetcher {

    private static final String LOG_TAG = "UrlFetcher";

    public static Task<byte[]> getUrl(String url) {
        final TaskCompletionSource<byte[]> tcs = new TaskCompletionSource<>();
        try {
            tcs.setResult(downloadUrl(url));
        } catch (IOException e) {
            tcs.setError(e);
        }
        return tcs.getTask();
    }


    private static byte[] downloadUrl(String myurl) throws IOException {
        InputStream is = null;
        try {
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            // Starts the query
            conn.connect();
            int response = conn.getResponseCode();
            Log.d(LOG_TAG, "The response is: " + response);
            is = conn.getInputStream();

            byte[] bytes = IOUtils.toByteArray(is);
            return bytes;
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

}

This is the first task to be run. How can I run it on a background executor?

It appears that it's only possible to specify an executor if another task is being continued.

Upvotes: 1

Views: 931

Answers (1)

Thomas Bouldin
Thomas Bouldin

Reputation: 3725

You don't need to use TaskCompletionSource, instead use Task.callInBackground:

public static Task<byte[]> getUrl(final String url) {
    return Task.callInBackground(new Callable<byte[]> {
        public byte[] call() {
            return downloadUrl(url);
        }
    });
}

Upvotes: 3

Related Questions