I'm a beginner with Android development, and I'm trying to make a practice app using MVVM. It's my first experience with this architecture, so I'm pretty unsure of everything that I do so far.
I'm trying to programmatically set the CollapsingToolBar's scroll flags. When the RecyclerView's list is empty, I'd like to disable the scrolling effect. When it has items, I reenable it.
In my ViewModel, I have:
@HiltViewModel
class MealsViewModel @Inject constructor(
private val mealDao : MealDao
) : ViewModel() {
\\ depending on the calendar day, grab the list of meals from the Room Database
private val currentDay: MutableLiveData<Date> = MutableLiveData(Date())
val meals = Transformations.switchMap(currentDay){ date -> mealDao.getMeals(date).asLiveData() }
\\ this is observed in the fragment; if meals is empty from database, return this int (scroll flag)
val enableOrDisableScroll = meals.map {
if (it.isNullOrEmpty()) AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL else
AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP or
AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or
AppBarLayout.LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED
}
In the Fragment, enableOrDisableScroll
is observed like so:
viewModel.enableOrDisableScroll.observe(viewLifecycleOwner) {
val params: AppBarLayout.LayoutParams = collapsingToolBar.layoutParams
as AppBarLayout.LayoutParams
\\ it is the returned value from the ViewModel observation
params.scrollFlags = it
collapsingToolBar.layoutParams = params
}
(This solution is modified from https://stackoverflow.com/a/32699543/11813571)
Is this proper MVVM design? Is all the "business logic" properly separated from the view (Fragment)? I may be having trouble understanding the term itself. In Android programming, is business logic anything that would decide how a view is created and UI updated? How could my MVVM approach be improved? It works as intended, but I don't know if it's optimal.
Thank you!