Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Android

Matthew Lee
Matthew Lee
6,715 Points

How can I wait for a function to finish before continuing?

Hi,

I have a function that calls an API and parses and then loads data into an array.

How can I wait for this function to finish before continuing with the rest of the code which uses the loaded data?

Best, Matt

2 Answers

Caleb Kleveter
MOD
Caleb Kleveter
Treehouse Moderator 37,862 Points

I am not very fluent in Java, so I don't know the best way to do this, but typically you use what is called a callback function. A callback is a function that is passed into another function as a parameter. Here is some basic pseudo code:

function getDataFromURL(url, callback) {
    // Get data here.
    // Pass that data into the call back function
    callback(data);
}

// Use the above function
getDataFromWeb("https://teamtreehouse.com/calebkleveter.json", function(data) {
    // Use the data passed in from the callback
});
Matthew Lee
Matthew Lee
6,715 Points

Thanks for the input!

Matthew Lee
Matthew Lee
6,715 Points

I was stuck on this for a couple of days but I called the function (the one I wanted to run after getting data from the API) in runOnUiThread() inside the OnResponse().