I'm having hard times with building my app that uses Firebase Realtime Database.
What I want to achieve:
I have two tables:
I want to get 10 songs that have not been guessed by current User yet.
I thought about method similar to that (pseudo-code) running in my Activity:
public List<SongPOJO> getTenUniqueSongs() {
List<SongPOJO> myList = new ArrayList<>();
int songId = 0;
while(myList.size() < 10) {
SongPOJO mySong = getASongFromTheDatabase(songId);
if (!checkIfSongExistsInTableGuessedSongs())
myList.add(mySong);
++songId;
}
}
I know how to write request to the Realtime database's reference (get dataSnapshot and check if dataSnapshot exists using exists() method). But that's not the case.
The problem is that I want to get this data synchronously in the main Thread (I will give the user some kind of waiting alert until this operation finishes successfully). But I don't know how to do that.
I've done some research and I was trying to implement this solution: https://stackoverflow.com/a/45308259/5834189 using TaskCompletionSource . But the thing is it cannot be run in the main Thread. I know I can handle this using AsyncTask but I have no idea how to get the data synchronously.
I completely understand that working with the database means making asynchronous calls, but how to get data in a specific moment?
Could you please help me with finding the solution? Multithreading seems to be really mysterious to me at the moment.