Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing executor for current thread

I'm using ListenableFuture from Guava, and one nice thing about them is that one pass Executor to the Futures.addCallback method, that is, ask to execute the callback on a given thread/executor.

In my Android application, I want to be able to start the asynchronous execution based on ListenableFuture in the UI thread, and schedule a callback which is also executed also on the UI thread. Therefore, I'd like to somehow submit the UI thread executor to the Futures.addCallback method mentioned above. How to achieve that?

Or, in other words, I want to have an executor for the UI thread. Is it available already in Android, or, if I have to create my own, how do I do that?

EDIT: As an extension to this question, is it possible to do same thing, but not just with UI thread, but with any particular thread, where the call to async method is made?

I would be happy to know how to achieve the same effect without resorting to the Android-specific stuff like Handler and Looper, just with pure Java.

like image 635
Haspemulator Avatar asked Jan 21 '14 11:01

Haspemulator


2 Answers

For Android UI thread executor use:

ContextCompat.getMainExecutor(context)

like image 67
solidogen Avatar answered Sep 25 '22 14:09

solidogen


Use com.google.android.gms.tasks.TaskExecutors.MAIN_THREAD.

An Executor that uses the main application thread.

Source: Android docs

The tasks APIs are part of Google Play services since version 9.0.0.

like image 24
Niels Avatar answered Sep 22 '22 14:09

Niels