Be onClickListener and onLongClickListener for recyclerView items in ViewModel or Fragment? Why?
First one get onClickListener from viewModel:
class MyFragment : Fragment() {
...
private fun setUpAdapter() = MyAdapter({ todoEntity, todoTitle ->
viewModel.onClickListener(todoEntity, todoTitle)
}, { todoEntity: TodoEntity ->
viewModel.onTodoLongClick(todoEntity)
})
...
}
Second one get onClickListener in Fragment:
class MyFragment : Fragment() {
...
private fun setUpAdapter() = MyAdapter({ todoEntity, todoTitle ->
onClickListener(todoEntity, todoTitle)
}, { todoEntity: TodoEntity ->
onTodoLongClick(todoEntity)
})
fun onClickListener(todoEntity: TodoEntity, todoTitle: TextView) {
// Do Something
}
fun onTodoLongClick(todoEntity: TodoEntity) {
// Do Something
}
...
}
Which one is better?
In the view, the fragment. The ViewModel should have no knowledge whatsoever from the View, so common practive would be:
The listener is set in the view, but the actual code lives in the viewmodel. The fragment should be as small as possible and only connects the layout and its' lifecycle with the behaviour in the ViewModel.