How to wait inside a method, till other method is completed

389 views Asked by At

Let's say we have this code:

int number;

public void onMessageReceived(int num) {
    number = num;
}

public int getNumber() {
    sendMessage("number")
    return number;
}

you get the Message only after lets say 1 second.

How do you "wait" until you get the "number" without freezing the Main-Thread?

public int getNumber() {
    sendMessage("number")
    //WAIT TILL I GET THE "NUMBER"
    return number;
}
4

There are 4 answers

0
iouhammi On

This kind of asynchronous calls need some callback mechanisms.

You may need to use an observer design pattern that subscribe into an event call.

See this link

Or try to use CallbackTask like in this question:

java-executors-how-to-be-notified-without-blocking-when-a-task-completes

5
Crembo On

You probably want to use something like Java Future.

Have a look at the docs or read up this simple example.

5
Rookie007 On

May be recursive methodlogy

public int getNumber() {

 while(number!=0)
 getNumber(); //Assuming number will not be null till you get positive integer greater than a zero same method will get recalled.
 sendMessage("number")

return number;
}

When onMessageReceived(int num) called then you can find a positive integer in number so that it will countinue the execution

0
Shailesh Yadav On

You should use join method...

When a thread calls join() on another thread, the currently running thread will wait until the thread it joins with has completed.