1

Example:

Sync Vesrion:

int weather = getWeather();

Async version:

getweather(callback) to the other class and when other class ready to return value it use callback. callback.receiveWeather(temperature); and callback object has a overridden receiveWeather(int) method.

Question:

now how do i convert async method to sync call in android. can you give me a example ? i know it has something to do thread , wait() etc .. but do not know to implement it.

user3456901
  • 13
  • 1
  • 5
  • Note that you generally should not call (and often will be unable to get a result returned from) such a method on the UI thread. – Chris Stratton Apr 24 '16 at 05:21
  • @ChrisStratton I think this question has a value, because such conversion can be useful if you are already in an `AsyncTask`, and trying to avoid a long chain of async call, writing one line of code per call. – kftse May 18 '16 at 20:38

2 Answers2

1

The following code does what you want, but it is far more preferable to just create a blocking getter and wrap it with AsyncTask in case async routine is also needed.

When this is nested, be sure not to

  • wait() the main thread
  • run both segments in the same thread

Especially if you wrap some async only API with not well documented threading mechanism, this can make both method running on the same thread.

public class AsyncToSync{

    private Object lock= new Object();
    private boolean ready = false;

    public syncCallToAsyncMethod(){

        new AsyncMethodProvider().doAsync(new CompletionListener(){

            public void onComplete(){
                // TODO: Do some post-processing here

                synchronized(lock){
                    ready = true;
                    lock.notifyAll();
                }
            }

        })

        synchronized (lock) {
            while (!ready) {
                try {
                    lock.wait();
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
        }

    }
}

See Guarded Blocks.

kftse
  • 191
  • 2
  • 18
-1

In the called method, instead of calling the callback method and passing in the result, just return the result. So change the method signature from this:

public void getWeather(WhateverCallback<Type> callback)

To this:

public Type getWeather()
nasch
  • 5,330
  • 6
  • 31
  • 52
  • If you can change the getWeather method then your response is obvious. I suppose OP (like me now) can't change that method, and want to wrap the callback mechanism in a sync call. – Anthony Sep 10 '19 at 08:44
  • @Anthony I would never assume what is and what is not obvious to someone else on this site. For example, I once had a discussion with someone about whether a piece of text was the name of a variable or not. – nasch Sep 10 '19 at 14:29