oday
01/17/2019, 7:30 PMjalexdev
01/18/2019, 11:20 PModay
01/21/2019, 1:52 PMjalexdev
01/22/2019, 6:37 PMyes, but that layer, will it be a base viewmodel? a separate class?Prefer Composition over Inheritance -> Separate class. Classes that expose shared data often are represented with the Repository Pattern so I'd recommend having the class be named as
<Something>Repository
.
a class with specific functions that each viewmodel can inject into itself?Yes each ViewModel should inject the shared data providing Repository. Google Architecture guidance also suggest this: https://developer.android.com/jetpack/docs/guide#connect-viewmodel-repository.
how would you provide a subscriber that tells that class what to do when its done calling those shared functions? cause each viewmodel is going to have to do something else with the end result of that class’ workThe Repository should expose Rx Observables or LiveData which can then transformed by each ViewModel (using Rx operators or LiveData Transformations).
it has to be another viewmodelIt could be another ViewModel but the real requirement I'm guessing you have is that the Repository instance must be shared\reused across the consumers of this shared data. This requirement is usually because your shared data is maintained in runtime memory. If the data is persisted then you could get away with different instances of the Repository however this can lead to other challenges such as avoiding duplication of syncing data with a remote source. There are multiple strategies to share the Repository instance between your different ViewModels such as: - Expose the Repository from a ViewModel mapped to a parent (view hierarchy wise) Activity\Fragment. This requires the consumers Android views be Fragment and and not an Activity. The child fragments can then fetch the ViewModel instance of the parent Activity\Fragment to fetch the Repository instance. This is similar to your statement for having another ViewModel to host the shared data. The only difference here is that I suggest factor out the actual data logic into a Repository class. This make the intent of the class clearer and can be reused in other places if ever needed. - Expose the Repository as a Singleton either via Application class or a top level lazy variable. Tradeoff here is the pattern is simple but at the cost of bloating your app state if the Repository isn't needed all the time. As your app scales you'll find that a DI framework like Dagger to abstract the strategies above could also become useful but that's a different discussion and not a requirement to your problem.