Can Runnable return a value?

Is it possible for Runnable to return a value? I need to carry out intensive work on the editable, and then bring it back. Here is my code layout.

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 that I am trying to modify finalEdit, but it must be final in order to access it in and out of the stream, right? What is the right way to do this?

+6
source share
4 answers

In Java, Runnable cannot "return" a value.

On Android, specifically the best way to deal with your type of script is AsyncTask . This is a generic class so that you can specify the type you want to pass and the type returned by the onPostExecute function.

In your case, you will create AsyncTask<Editable, Void, TypeToReturn> . Sort of:

 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 } } 
+2
source

You understand that the stream continues to work after the workOnEditable () function completes, right? If you want a synchronous response, get rid of the thread. If not, use a handler to transfer data back to the main stream.

+2
source

The following exists, simply pointing to 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 Christopher Martin's Java Pseudo Closures, skip to the "Faking it" section. It introduces the mutable type ValueHolder<T> :

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

Happy coding.

+1
source

I made two utility methods around Runnable that allow you to send runnable and block until you get the result.

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

0
source

Source: https://habr.com/ru/post/899752/


All Articles