๐์ฐธ๊ณ ์๋ฃ
๐์ฐธ๊ณ ํ๋ฉด ์ข์ ์ง๋ ํฌ์คํ
StateFlow
, SharedFlow
:Flow
, StateFlow
is hot๐์ฐธ๊ณ ์๋ฃ
- Migrating from LiveData to Flows: An Engineerโs Guide | Kerry Bisset
- [Kotlin] Flow๋ฅผ StateFlow๋ก ๋ณํ | th.k
val myStateFlow = myFlow.stateIn( scope = lifecycleScope, started = SharingStarted.Lazily, initialValue = ์ด๊ธฐ๊ฐ )
๐์ฐธ๊ณ ํ๋ฉด ์ข์ ์ง๋ ํฌ์คํ
MutableLiveData
๋ฅผ MutableStateFlow
๋ก ๋ฐ๊พธ๊ธฐ!MutableLiveData
์ ํน์ง:MutableStateFlow
์ ํน์ง:value
ํ๋กํผํฐ๋ก value get & setMutableLiveData
// Observing LiveData in an Activity or Fragment
personNameLiveData.observe(this, Observer { name ->
// Update UI with the new name
})
MutableStateFlow
lifecycleScope
์ง์ , Lifecycle.repeatOnLifecycle
๋ธ๋ก ์ฌ์ฉ)// Collecting StateFlow in a Coroutine
lifecycleScope.launch {
personNameStateFlow.collect { name ->
// Update UI with the new name
}
}
MediatorLiveData
๋ง์ด๊ทธ๋ ์ด์
๋ฐฉ๋ฒ:
์ฌ๋ฌ MutableStateFlow
๋ฅผ combine/zipํ์ฌ Flow
๋ก ํฉ์น๊ธฐ!
ImageSearch ํ๋ก์ ํธ SearchViewModel.kt ๋ง์ด๊ทธ๋ ์ด์ ์
private val _searchItems = MutableLiveData<List<Item>>(emptyList())
val searchItems: LiveData<List<Item>> get() = _searchItems
private val _savedItems = MutableLiveData<List<Item>>(emptyList())
val savedItems: LiveData<List<Item>> get() = _savedItems
private val _resultItems = MediatorLiveData<List<Item>>().apply {
val onChange = { _: List<Item> ->
value = searchItems.value!!.map { item ->
savedItems.value!!.find { it.id == item.id }?.let {
item.copy(folderId = it.folderId)
} ?: item.copy(folderId = FolderId.NO_FOLDER.id)
}
}
addSource(searchItems, onChange)
addSource(savedItems, onChange)
}
val resultItems: LiveData<List<Item>> get() = _resultItems
ImageSearch ํ๋ก์ ํธ SearchViewModel.kt ๋ง์ด๊ทธ๋ ์ด์ ํ
private val _searchItems = MutableStateFlow<List<Item>>(emptyList())
private val searchItems: StateFlow<List<Item>> get() = _searchItems
private val _savedItems = MutableStateFlow<List<Item>>(emptyList())
val savedItems: StateFlow<List<Item>> get() = _savedItems
private val _resultItems =
searchItems.combine(savedItems) { searchItems, savedItems ->
searchItems.map { item ->
savedItems.find { it.id == item.id }?.let {
item.copy(folderId = it.folderId)
} ?: item.copy(folderId = FolderId.NO_FOLDER.id)
}
}
val resultItems: Flow<List<Item>> get() = _resultItems