I'm trying to consume a boolean from Proto DataSto...
# android
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? ``````
o
Call the other stateIn() method (https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/state-in.html). Example:
Copy code
val isLoggedIn: StateFlow<Boolean> = mainRepository.userPreferencesFlow.map { it.isLoggedIn }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), initialValue =false)
💯 1
🤩 1
👍 1
❤️ 1
r
Thank you! It worked like charm🤩.
m
I had the same problem like you couple days ago with replacing liveDate with stateFlow. Why do you need stateIn operator ? You just need simplifiest as you can but your example its not.
g
You can add own extension function for it But it's tight approach if you need StateFlow Scope is required to make it Lifecycle safe (unsubscribe from upstream flow on scope cancellation), you should provide initial value, because flow has StateFlow.value property (suspend version of stateIn just suspend until first value is received) and you need should explicitly specify sharing startegy, which works better for or your case, should it be eager (subscribe immediately, unsubscribe only on cancellation), lazy (subscribe on first subscriber, unsubscribe on cancellation) or WhileSubsceibed (subscribe on first subscriber, unsubscribe when no subscribers) You don't need any of those state in operators if instead of using StateFlow you consume it just as Flow, it's cold by default, doesn't require any additional operators
k
Why can't you just unsubscribe in onStop() like you do with Rxjava's CompositeDisposable?