I'm trying to consume a boolean from Proto DataSto...
# coroutines
r
I'm trying to consume a boolean from Proto DataStore as an observable StateFlow but couldn't. #StateFlow
Copy code
val isLoggedIn: StateFlow<Boolean> = mainRepository.userPreferencesFlow.map { it.isLoggedIn }.stateIn(viewModelScope )
The above code gives me the error: "Suspend function 'stateIn' should be called only from a coroutine or another suspend function" I could do it with LiveData like below. #LiveData
Copy code
val isLoggedInLiveData: LiveData<Boolean> =
    mainRepository.userPreferencesFlow.map { userPreferences ->
        userPreferences.isLoggedIn
    }.asLiveData()
Can anyone suggest an equivalent code for StateFlow? `````` Slack Conversation
j
looks like you're using following version of
stateIn
Copy code
public suspend fun <T> Flow<T>.stateIn(scope: CoroutineScope): StateFlow<T> {
but want to use following version
Copy code
public fun <T> Flow<T>.stateIn(
    scope: CoroutineScope,
    started: SharingStarted,
    initialValue: T
): StateFlow<T>
example from some code here....
Copy code
val peopleInSpace = peopleInSpaceRepository.fetchPeopleAsFlow()
            .stateIn(viewModelScope, SharingStarted.WhileSubscribed(), emptyList())
❤️ 1
💯 1
👍 1
r
Thank you! It worked like charm🤩
The solution with StateFlow is below.
Copy code
val isLoggedIn: StateFlow<Boolean> = mainRepository.userPreferencesFlow
    .map { it.isLoggedIn }
    .stateIn(viewModelScope, SharingStarted.WhileSubscribed(), false)