Android 12 splash screen setKeepVisibleCondition

Viewed 925

I'm trying to implement a splash screen using android 12 SplashScreen compat library. I want to fetch some data from API each time my app starts. So the splash screen should wait until the API calls finish. I found this splashScreen.setKeepVisibleCondition() function in docs, but don't know how to implement KeepScreenOnCondition. How can I make my splash screen to wait? Any help would be appreciated.

3 Answers

found the solution.

private var isLoading = true

override fun onCreate(savedInstanceState: Bundle?) {
    val splashScreen = installSplashScreen()
    splashScreen.setKeepVisibleCondition { isLoading }
}

private fun doApiCalls(){
    ...
    isLoading = false
}

@sujith's answer did not work for me for some reason.

I added a method in my viewModel like this:

fun isDataReady(): Boolean {
    return isDataReady.value?:false
}

and used

splashScreen.setKeepVisibleCondition {
    !viewModel.isDataReady()
}

This worked for me. May be someone can explain to me why sujiths answer was not working for me( it was hiding the splash screen after some time). Because I know both of us are essentially doing the same thing.

Expanding on @hushed_voice's answer, setKeepVisibleCondition() will keep the Splash Screen on as long as it's returning true. Once it equates to false, the Splash will finish and your app will proceed forward.

Here is a short function I wrote up to handle my Splash Screen logic in my Main Activity:

private fun splashScreen() {
    val splash = installSplashScreen()
    splash.setKeepVisibleCondition{
        viewModel.initialize()
    }
}

Inside my ViewModel, the initialize() function does some asynchronous work, after which it returns false.

fun initialize(): Boolean {
    return !isDataReady
}

Till then my Splash Screen is present, after which it goes away. You should be able to throw in your API calls in this block and use a Reactive library to wait for them to complete before returning false. This is working perfectly for me.

Related