Can a Runnable return a value?
Asked Answered
B

4

6

Is it possible for a Runnable to return a value? I need to do some intensive work on an Editable and then return it back. Here is my mock code.

public class myEditText extends EditText {
...
private Editable workOnEditable() {
    final Editable finalEdit = getText();
    Thread mThread = new Thread(new Runnable() {
        public void run() {


              //do work

              //Set Spannables to finalEdit

        }
     });
    mThread.start();
    return finalEdit;
}
...
}

So obviously my first problem is I'm trying to change finalEdit, but it has to be final in order to access it in and out of the thread, right? What's the correct way to do this?

Beeson answered 21/10, 2011 at 2:47 Comment(1)
Runnable can't but Callable can. Use with an Executor.Jacobs
E
2

In Java, a Runnable cannot "return" a value.

In Android specifically, the best way to handle your type of scenario is with AsyncTask. It's a generic class so you can specify the type you want to pass in and the type that is returned to the onPostExecute function.

In your case, you would create an AsyncTask<Editable, Void, TypeToReturn>. Something like:

private class YourAsyncTask extends AsyncTask<Editable, Void, Integer> {
     protected Long doInBackground(Editable... params) {
         Editable editable = params[0];
         // do stuff with Editable
         return theResult;
     }

     protected void onPostExecute(Integer result) {
         // here you have the result
     }
 }
Emalia answered 21/10, 2011 at 3:47 Comment(0)
D
1

The following exists simply to point out the use of "pseudo-closures" in Java, as unsuitable as they may be in this case.


Java allows pseudo-closures through mutable-types stored in final variables.

See Java's pseudo-closures by Christopher Martin skip to the "Faking it" section. He introduces a mutable-type ValueHolder<T>:

private static class ValueHolder<T> {
  T value;
}
...
final ValueHolder<Integer> i = new ValueHolder<Integer>();
...
i.value = 42;

Happy coding.

Diallage answered 21/10, 2011 at 2:53 Comment(0)
M
1

You realize that the thread keeps working past the end of the workOnEditable() function, right? If you want a synchronous response, get rid of the thread. If not, use a Handler to pass the data back to the main thread.

Monkery answered 21/10, 2011 at 2:54 Comment(0)
L
0

I have made 2 utility methods around Runnable that enable you to post a runnable and block until you get the result.

You can take a look here: https://github.com/Petrakeas/HVTHandler/

Lythraceous answered 12/10, 2015 at 23:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.