0

Is there any way to return value (or just return;) for the outer function from the inner function?

My question is similar to this question: Breaking out of nested loops in Java, but the difference is that in this question the asker asked about breaking the outer loop in nested loops, and I ask about returning for the outer function in nested functions.

public void outerFunction ()
{
    runOnUiThread (new Runnable()
    {
        @Override
        public void run ()
        {
            // Here i want to return;, so the function will not continue after runOnUiThread
        }
    });

    // Code here should not run.

}
Community
  • 1
  • 1
Or B
  • 1,675
  • 5
  • 20
  • 41
  • 2
    What you are looking at is, annoymous thread instance as part of method invocation, not function/method inside function/method. – kosa Sep 10 '13 at 19:42

2 Answers2

1

The method runOnUiThread accepts a Runnable argument. We can assume it uses its run() method somewhere. For example, if the method was

public void runOnUiThread(Runnable runnable) {
    // do a bunch of stuff
    // some more logic
    runnable.run();
    // more logic
    return;
}

You can't force a return of the calling method (runOnUiThread()) from the called method (run()). You can however throw an Exception within the called method that will stop all execution, but you won't necessarily know where that gets caught.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
0

I'm not sure I understand the question. But I assume you are not very familiar with multi-threading.

The code within Runnable and the code after the call to runOnUiThread actually run at the same time, but on different threads. So it is light-years away from nested loops, or from single-threaded nested methods calls.

You can actually make a "blocking" call to another thread to wait for a value, but I don't think it's appropriate to write all of this out in a stackoverflow answer. You should read up on multi-threading and I strongly recommend Java Concurrency in Practice. But you should be warned that it is not a trivial topic that you can pick up in a few days. You can also look at this tutorial; the interface Future implements the "blocking" call I was referring to.

EDIT
I wrote the above thinking in Java. Things are more complicated with Android since in order to use a Future, you would need to get an ExecutorService for the UI thread, and I'm not sure that is possible.

There are many Android specific multi-threading constructs (see for example this tutorial, or the official doc). It is certainly possible to solve your problem, but we don't have enough details. Also, you should probably not try to find a quick fix for your problem, but rethink your whole design so that fits naturally within the Android multi-threading paradigm.

toto2
  • 5,306
  • 21
  • 24