Jetpack Compose collectAsState issue

Viewed 2223

I'm using Composes collectAsState() function to collect from this StateFlow

val _authToken = MutableStateFlow(AuthToken("", 0))
val authToken: StateFlow<AuthToken> = _authToken
val authToken by loginViewModel.authToken.collectAsState() // this returns AuthToken which is fine.

However, when turning a cold flow into a stateflow using the stateIn operator then using collectAsState() it returns a State version of the object which is odd then I need to call .value on collectAsState() to retrieve it.

Does anyone know why this happens?

val user = repository.getUser(viewModelScope).stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), null)
val user = profileViewModel.user.collectAsState() // returns State<User>
3 Answers

Replace

val user = profileViewModel.user.collectAsState() 

With

val user by profileViewModel.user.collectAsState() 

Well it IS supposed to return State. Compose offers the delegate syntax to allow you to treat state as raw types.

If you want to extract the data from State, you make use of the by keyword. For example,

var a : T by b : State<T> and, var a : State<T> = b : State<T>

In your case, if you want user to be of type User and not State<User>, you should change the initialisation to

val user by profileViewModel.user.collectAsState() // returns User

Also, you should have known from the name of the method, it is collectAsState.

With the new version for androidx.lifecycle:lifecycle-*:2.6.0-alpha01, use collectAsStateWithLifecycle() instead

Related