简体   繁体   中英

How to inject viewmodel in a customView with koin?

I know how to inject viewmodel in Activities or Fragments with koin:

private val regionSelectorViewModel: RegionSelectorViewModel by viewModel()

Right now I am setting viewmodel to my customView like this:

fun setViewModel(viewModel: RegionSelectorViewModel) {
    mViewModel = viewModel
}

The viewmodel is initialized in Activity and passed through parameter to view. But... I would like to inject viewmodels in customViews as I do in the activities or fragments. Is there a way to do that using koin?

In the end I got a solution for this problem, we only have to get viewmodel from activity context:

  private val viewModel: VersionViewModel by lazy {
    (context as FragmentActivity).getViewModel()
  }

Another solution, or for me the best solution is create a delegate to get viewmodel from a view.

inline fun <reified T : ViewModel> ViewGroup.viewModel(): ReadOnlyProperty<ViewGroup, T> =
  object : ReadOnlyProperty<ViewGroup, T> {

    private var viewModel: T? = null

    override operator fun getValue(
      thisRef: ViewGroup,
      property: KProperty<*>
    ): T = viewModel ?: createViewModel(thisRef).also { viewModel = it }

    private fun createViewModel(thisRef: ViewGroup): T {
      return (thisRef.context as FragmentActivity).getViewModel()
    }
  }


class CustomView @JvmOverloads constructor(
  context: Context,
  attrs: AttributeSet? = null,
  defStyleAttr: Int = 0,
  defStyleRes: Int = 0
) : FrameLayout(context, attrs, defStyleAttr, defStyleRes) {

  private val viewModel: CustomViewModel by viewModel()
  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM