-
Couldn't load subscription status.
- Fork 0
Concepts involved in application
Devrath edited this page Mar 26, 2022
·
4 revisions
- The reactive data source is very useful in keeping the code decoupled
- We can keep the data in the view model as
reactiveand make it such a way that it is being observed in the view layer(activity/fragment) - This way we can prevent memory leaks
- A memory leak happens when the
fragmentis destroyed and the reference is kept in theview model
private val _eventChannel = Channel<Event>()
val events = _eventChannel.receiveAsFlow()- We use a methodology where we keep a channel in the
view modelwe make it private and such a way that user won't be able to add values to the channel - By converting the channel to flow and making it public user can observe the value in the fragment and not add values in the fragment.
private val refreshTriggerChannel = Channel<Refresh>()
private val refreshTrigger = refreshTriggerChannel.receiveAsFlow()
val breakingNews = refreshTrigger.flatMapLatest { refresh ->
// Get data from repository
}.stateIn(viewModelScope, SharingStarted.Lazily,null)-
stateInconvertscold flowinto ahot flow---> its like a water gyezer (Haha) - We used stateIn with
flatMapLatestin theview modelbecause using the stateIn we can ensure that the latest value is returned to the fragment when the device rotates, Here we do not execute entire block again. - We gave
SharingStarted.Lazilyfor thestateInbecause we make it in such a way that the flow becomes active when invoked. - Now
breakingNewsis a reactive data source that we observe in the view layer
-
View-Modelrequests the data from the repository, Now it is the responsibility of the repository to get the data from any sources needed and return to the ViewModel then fragment updates it in its view. - So a repository returns a flow.
- We shall use a helper mechanism called
network bound resourceand facilitate this based on the logic we define.
