Waiting for some function complete in android

Viewed 44

in my android app(media player), i'm scanning all media files in loadingActivity.kt file. and then starting mainActivity.kt. my code is

scanSongs()
intent = Intent(this, MainActivity::class.java)
startActivity(intent)

and my scanSongs() function is

private fun scanSongs() {
        val songsJob = async {
            val songsFinder = SongsLoader(contentResolver)
            songsFinder.load()
            songsFinder.getAllSongs()
        }
        launch {
            allSongsList = songsJob.await()
            allSongsList?.sortBy { it.getTitle() }
        }
    }

but before scan complete it is opening mainActivity . and showing empty list . how can i waiting for complete scanSong() , before open mainActivity

2 Answers

Open the MainActivity when you have the allSongsList:

private fun scanSongs() {
        val songsJob = async {
            val songsFinder = SongsLoader(contentResolver)
            songsFinder.load()
            songsFinder.getAllSongs()
        }
        launch {
            allSongsList = songsJob.await()
            allSongsList?.sortBy { it.getTitle() }
            intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
        }
    }

You have to check a condition before start mainactivity.kt that

song list is null or not

Related