Skip to content

Instantly share code, notes, and snippets.

@wojtek-kalicinski
Last active March 11, 2021 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wojtek-kalicinski/ae368e7a8cb6277d0a755b14872a1439 to your computer and use it in GitHub Desktop.
Save wojtek-kalicinski/ae368e7a8cb6277d0a755b14872a1439 to your computer and use it in GitHub Desktop.
LiveData->StateFlow conversion
class ProfileViewModel : ViewModel() {
private val _name = MutableStateFlow("Ada")
private val _lastName = MutableStateFlow("Lovelace")
private val _likes = MutableStateFlow(0)
val name: StateFlow<String> = _name
val lastName: StateFlow<String> = _lastName
val likes: StateFlow<Int> = _likes
// popularity is exposed as StateFlow using a transformation and the stateIn operator.
val popularity: StateFlow<Popularity> = _likes.map {
when {
it > 9 -> Popularity.STAR
it > 4 -> Popularity.POPULAR
else -> Popularity.NORMAL
}
}.stateIn(viewModelScope, SharingStarted.Eagerly, Popularity.NORMAL)
fun onLike() {
_likes.value = _likes.value + 1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment