Display the first screen once data is loaded in background on Android

55 Views Asked by At

I am using all the Modern Android Development stack (Compose UI and Navigation, ViewModels etc.) with Preferences DataStore to store the AuthState (from AppAuth).

I have an issue when loading the initial state of the application. I want to either load the login screen or the home screen depending on the authentication state.

I am not really satisfied with the solution below. Because DataStore interaction is asynchronous, there is a small delay before being able to determine the first screen. If I don't "protect" the AppScreen composable with the if statement, it will quickly show the login screen before navigating to the home screen when the user is already authenticated.

Do you have any suggestions or better way to achieve this?

@AndroidEntryPoint
class MainActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val viewModel: AppViewModel by viewModels()

        setContent {
            val authState by viewModel.appState.collectAsState()

            // maintain splashscreen while loading initial state
            val view = LocalView.current
            view.viewTreeObserver.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener {
                override fun onPreDraw(): Boolean {
                    return if (authState != AppState.INITIALIZING) {
                        view.viewTreeObserver.removeOnPreDrawListener(this)
                        true
                    } else {
                        false
                    }
                }
            })

            MyAppTheme {
                if (authState != AppState.INITIALIZING) {
                    AppScreen(viewModel = viewModel)
                }
            }
        }
    }

}
1

There are 1 best solutions below

2
On

I faced this issue, just show splash screen until you conditional work is not done, when its done show a particular page