Last active
March 11, 2021 13:15
-
-
Save wojtek-kalicinski/ae368e7a8cb6277d0a755b14872a1439 to your computer and use it in GitHub Desktop.
LiveData->StateFlow conversion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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