androidandroid-recyclerviewdagger-2dagger-hiltrecyclerlistview

Inject viewModel with hilt


I want to inject my viewModel inside RecyclerView with Hilt. It can be inject but viewModel not destroy when recyclerView destroyed. what is the best way to inject viewModel inside recyclerView with hilt?


Solution

  • The best way to do this is to create separate adapter and viewholder classes and then you can inject your viewModel inside that viewholder class instead of the adapter. To destroy the viewModel you should manually do it by observing the parentlifecycle. when the parent lifecycle event is ON_DESTROY do something similar to this in the init block of the adapter class.

    parentLifecycle.addObserver(object : LifecycleObserver {
    
                @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
                fun onParentDestroy() {
                    recyclerView?.run {
                        for (i in 0 until childCount) {
                            getChildAt(i)?.let {
                                (getChildViewHolder(it) as BaseItemViewHolder<*, *>)
                                    .run {
                                        onDestroy()
                                        viewModel.onManualCleared()
                                    }
                            }
                        }
                    }
                }
      }
    

    Here onManualCleared() function calls onCleared().