# android


03/11/2024, 11:22 AM
Is it possible to initialize values in ViewModel from values retrieved from proto datastore ?
not kotlin but kotlin colored 2
New to Jetpack Compose and Android development, I was simply trying to achieve these basic steps : 1. When ViewModel is initialized, retrieve user data stored in proto datastore just once. 2. Based on the values of user data, initialize other variables in the View Model. Perform operations on these variables to build an uiState. 3. Update that uiState based on UI interactions. Update user data in proto datastore on specific conditions. However, apparently proto datastore only emits a flow, and synchronous operations are not advised in the documentation. For now, I'm getting this flow in my ViewModel as follows :
val userDataFlow : Flow<UserData> = appRepository.userDataFlow
I know I can convert this to a StateFlow and collect this StateFlow in the UI layer, but I just need to retrieve the values stored in datastore during initialization, perform some operations on them, and possibly update them later based on how user interacts with UI. Is such scenario possible ? This is a basic usecase, and I'm surprised it's quite difficult to apprehend for a beginner. I'm currently wondering if I shouldn't just manually write user data to a simple
file and fetch them during initialization. Thank you very much for your help.
So, I have 2 possibilities, either :
Copy code
    userData = appRepository.userDataFlow.first()
    // Then, initialize other variables in ViewModel who depends on the value of userData (and pass    //these value to other functions to do the initialization).
Or :
Copy code
val uiStateFlow = appRepository.userDataFlow
    .map { userData -> calculateMyVariableFromUserData(userData) }

init {
   userData = uiStateFlow.value
Are these 2 approaches good ?


03/11/2024, 3:59 PM
Have u checked what chatgpt says?