Mateusz Holak
11/23/2020, 3:55 PMLiveData<X>.map {} => transform type MutableLiveData<DomanType> -> LiveData<UiType>
I would like replace LiveData with StateFlow but i need to transform domain type to UI type that i have for each layers. Which one method i should use ? The same method "map" in Flow return Flow<R> but i need StateFlow<T>. I can also do transormation when i have data from useCase and then assign MutableStateFlow to StateFlow by invoking asStateFlow but its a little worse solution than i have with LiveData right now. Thanks for any advice.
I found similar question here:
https://github.com/Kotlin/kotlinx.coroutines/issues/2008Adam Powell
11/23/2020, 4:15 PMMateusz Holak
11/23/2020, 4:24 PMprivate val _characters by lazy {
MutableStateFlow<List<Character>>(emptyList()).also {
getCharacters(it)
}
}
val characters: StateFlow<List<CharacterDisplayable>> by lazy {
_characters.map {
characters ->
characters.map { CharacterDisplayable(it) }
}.stateIn(viewModelScope, SharingStarted.Lazily, emptyList())
}
In Fragment
private fun observeCharacters() {
lifecycleScope.launch {
viewModel.characters.collect {
showCharacters(it)
}
}
}
And this is version with LiveData
private val _characters by lazy {
MutableLiveData<List<Character>>().also {
getCharacters(it)
}
}
val characters: LiveData<List<CharacterDisplayable>> by lazy {
_characters.map { characters ->
characters.map { CharacterDisplayable(it) }
}
}
Mateusz Holak
11/23/2020, 4:32 PMAdam Powell
11/23/2020, 5:34 PM_characters
exist in that class?Mateusz Holak
11/23/2020, 6:39 PMAdam Powell
11/23/2020, 6:51 PM_characters.value
with the original list, why not perform the transformation directly when you would otherwise assign it? i.e.
private val _characters = MutableStateFlow<List<CharacterDisplayable>>(emptyList())
fun setCharacters(characters: List<Character>) {
_characters.value = characters.map { CharacterDisplayable(it) }
}
val characters: StateFlow<List<CharacterDisplayable>> get() = _characters
Adam Powell
11/23/2020, 6:51 PMMateusz Holak
11/23/2020, 7:06 PMAdam Powell
11/23/2020, 7:06 PMMateusz Holak
11/23/2020, 7:08 PMval characters: StateFlow<List<CharacterDisplayable>> get() = _characters.asStateFlow()
What are differences when i will have more than one consumers in that case ?Adam Powell
11/23/2020, 7:18 PMCharacterDisplayable
list? None, except it'll be more efficient this way. 🙂 If other code needs the untransformed List<Character>
then things change a bit, but not much. You still want to keep things simple without intermediate StateFlows where you can.Mateusz Holak
11/23/2020, 7:28 PM