https://kotlinlang.org logo
Title
p

Paul Dhaliwal

10/21/2019, 2:25 PM
In my app I always retrieve data from a room database, display it, and then update the data over the network (and then animate the change in data). I’m wondering what the best approach would be using clean architecture. Currently in the ViewModel a coroutine is launched and from inside the coroutine a Use Case is executed to retrieve the data from the db, then the livedata object (observed by the view) is updated. After this a second Use Case is launched to retrieve the data from the network, and then the livedata is updated again. I would like to be able to simplify this so that the ViewModel doesn’t know about where the data is coming from (or the fact that it comes from db first then network), so that it simply executes one GetDataUseCase and inside the use case (or inside the repository if that is preferable) I will retrieve data from db first, push data back to the ViewModel, then retrieve data from network, and push the updated data to the ViewModel. What would be the best approach to achieve this? I thought about adding LiveData objects inside the UseCase or Repository however in order to observe these objects I need to give them a lifecycle owner, and also since the whole process is kicked off inside a coroutine inside the ViewModel, I’m not sure how to do that. I’ve also read that the UseCase should be a pure Java/Kotlin file so that it stays testable.
:stackoverflow: 1
Solved using Kotlin Flow
r

rkeazor

10/22/2019, 2:09 PM
Doesnt Room database have livedata integration
I would think it's best to use livedata. Because values are emitted automatically when the database is updated ...
p

Paul Dhaliwal

10/22/2019, 2:13 PM
They added support for Flows recently I believe in Room. The issue with LiveData for me was providing a LifeCycle owner. Since I wanted this to be handled in either the UseCase or Repository, I wasn’t sure what the solution would be. This way the Use Case emits a result once the data is returned from the database, then emits again when the network call is done, and in the View Model all it knows is that it asked for the data, without knowing that it comes from db first and then network.
r

rkeazor

10/23/2019, 1:03 AM
Yea that's what LiveData Transformations are for. But I guess if you dont need to do UI updates with the new data you can use viewmodel scope