0

i have a confusion about what code should be placed in view and what in viewmodel

for example click events

here is a snippet code of google ToDo app example for showing application architecture (Link):

//this code is placed in view (TasksFragment)
override fun onOptionsItemSelected(item: MenuItem) =
        when (item.itemId) {
            R.id.menu_clear -> {
                viewModel.clearCompletedTasks()
                true
            }
            R.id.menu_filter -> {
                showFilteringPopUpMenu()
                true
            }
            R.id.menu_refresh -> {
                viewModel.loadTasks(true)
                true
            }
            else -> false
        }

private fun showFilteringPopUpMenu() {
    val view = activity?.findViewById<View>(R.id.menu_filter) ?: return
    PopupMenu(requireContext(), view).run {
        menuInflater.inflate(R.menu.filter_tasks, menu)

        setOnMenuItemClickListener {
            viewModel.setFiltering(
                when (it.itemId) {
                    R.id.active -> TasksFilterType.ACTIVE_TASKS
                    R.id.completed -> TasksFilterType.COMPLETED_TASKS
                    else -> TasksFilterType.ALL_TASKS
                }
            )
            viewModel.loadTasks(false)
            true
        }
        show()
    }
}

as you can see there are 3 three items for a menu

2 of them delegated to viewmodel and one handled in view

beside that there are some logic in view that make decision based on view's id, but in mvvm definition said there must be no condition in view

3
  • It isn't using a condition, it is setting a filter. The distinction is important. Feb 12 '20 at 15:58
  • @BobDalgleish but what about the task that delegate them to viewmodel and other that handle it itself?
    – hamid_c
    Feb 12 '20 at 16:07
  • 1
    MVVM has fundamental difficulties with scaling and scope of responsibilities. You will run into similar issues. Feb 12 '20 at 16:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.