1

I'm trying to implement an onboarding screen on my app which uses jetpack compose, the screen will open only for the first time of using the app, and "onboarding" boolean value is saved on datastore preferences afterwards. if you know any better way to store datastore preferences i'd like to know too please, my minimal example that shows the problem:

val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
val ONBOARDING = booleanPreferencesKey("onboarding")

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        NearbyConnectionsApi.setContext(applicationContext)
        val onBoarding: Flow<Boolean> = baseContext.dataStore.data
            .map { preferences ->
                preferences[ONBOARDING] ?: false
            }
        super.onCreate(savedInstanceState)
        setContent {
            val navController = rememberNavController()
            if(!onBoarding)//how to use the value here please
{
                navController.navigate("onboarding"){
                    popUpTo(0)
                }
            }
            //....screen implementation 
        }

how can i use the value of flow value please? thanks in advance

IdanB
  • 167
  • 1
  • 3
  • 13
  • 2
    check out [this answer](https://stackoverflow.com/a/69266511/3585796) – Phil Dukhov Feb 03 '22 at 10:37
  • Do you know please if how I can use the function youv'e made in non composable class please? – IdanB Feb 16 '22 at 23:14
  • You can't do that, because it uses compositional locals. But you can interact with the same data store only using the `context`, check out [documentation](https://developer.android.com/topic/libraries/architecture/datastore#preferences-datastore). Also if my [answer](https://stackoverflow.com/a/69266511/3585796) helped you, please give it an upvote. – Phil Dukhov Feb 17 '22 at 04:23

1 Answers1

0

You can collect the flow as state

setContent {
        val navController = rememberNavController()
        val onBoardingState = onBoarding.collectAsState(initial = false)


        if(!onBoarding.value)
        {
            navController.navigate("onboarding"){
                popUpTo(0)
            }
        }
        //....screen implementation 
}
Massimiliano
  • 120
  • 8