I have the following for loop.
for (song in songArray){
playSong(song)
}
and playSong as below:
fun playSong(song){
mediaPlayer.create(context, R.raw.song)
mediaPlayer.start
mediaPlayer?.setOnCompletionListener {
mediaPlayer!!.release()
mediaPlayer = null
}
}
The for loop does not wait for the entire playSong function to complete, and just immediately starts the next song. I want the the listener to be heard and the song to complete before iterating to the next song. If you could give me some guidance on this, I would appreciate it.
forloop does wait for the functionplaySongto finish. Your problem is thatplaySongfinishes immediately, not after the song finished playing, and the lambda you pass tosetOnCompletionListeneris only called later (afterplaySonghas returned). This is called asynchronous execution if you want to look it up. If you want to reason sequentially about these things you could make use of coroutines. Otherwise, you can use one of the options from the current answers.