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
John O'Reilly
11/29/2020, 5:10 PM
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>
John O'Reilly
11/29/2020, 5:11 PM
example from some code here....
Copy code
val peopleInSpace = peopleInSpaceRepository.fetchPeopleAsFlow()
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), emptyList())