Skip to content

Concepts involved in application

Devrath edited this page Mar 26, 2022 · 4 revisions

Role of reactive data source

  • The reactive data source is very useful in keeping the code decoupled
  • We can keep the data in the view model as reactive and 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 fragment is destroyed and the reference is kept in the view model

Usage of the channel in the view-model to show a one-time message

private val _eventChannel = Channel<Event>()
val events = _eventChannel.receiveAsFlow()
  • We use a methodology where we keep a channel in the view model we 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.

Using stateIn with flatMapLatest

private val refreshTriggerChannel = Channel<Refresh>()
private val refreshTrigger = refreshTriggerChannel.receiveAsFlow()

val breakingNews = refreshTrigger.flatMapLatest { refresh ->
   // Get data from repository
}.stateIn(viewModelScope, SharingStarted.Lazily,null)
  • stateIn converts cold flow into a hot flow ---> its like a water gyezer (Haha)
  • We used stateIn with flatMapLatest in the view model because 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.Lazily for the stateIn because we make it in such a way that the flow becomes active when invoked.
  • Now breakingNews is a reactive data source that we observe in the view layer

How the repository facilitates the data management between the api and the local db

  • View-Model requests 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 resource and facilitate this based on the logic we define.