3

This article explains how to use ViewModels in custom views :

class SummaryView(context: Context, attrs: AttributeSet?) : ConstraintLayout(context, attrs) {

  private val viewModel by lazy {
      ViewModelProvider(findViewTreeViewModelStoreOwner()!!).get<SummaryViewModel>()
  }

  override fun onAttachedToWindow() {
      super.onAttachedToWindow()

      viewModel.summaryModel.observe(findViewTreeLifecycleOwner()!!, ::populateSummaryView)
  }

}

It works well, but how can I use this technique using StateFlow instead of LiveData? How can I do this without having a reference to the fragment?

class SummaryView(context: Context, attrs: AttributeSet?) : ConstraintLayout(context, attrs) {

  private val viewModel by lazy {
      ViewModelProvider(findViewTreeViewModelStoreOwner()!!).get<SummaryViewModel>()
  }

  override fun onAttachedToWindow() {
      super.onAttachedToWindow()

      lifecycleScope.launch {
          viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
              viewModel.summaryModel.collect {

              }
          }
      }
  }

}
Greelings
  • 4,964
  • 7
  • 34
  • 70

0 Answers0