title: How to check if a ViewModel already exists for a given ViewModelProvider
body: <p><a href="https://www.droidcon.com/media-detail?video=380953203" rel="nofollow noreferrer">This video</a> (MVVM &amp; Nested Fragments/Views: ViewModel Contracts - By Marcos Paulo Damesceno, Bret Erickson
  droidcon San Francisco 2019
  ) shows a way to deal with communication between activities/fragments using <code>ViewModel</code>.</p>
  <p>I am implementing it for learning purpose but I got stuck.</p>
  <pre><code>// 18:35 of the video
  
  private const val VM_KEY = &quot;view_model_contract_key&quot;
  
  fun &lt;T&gt; Fragment.viewModelContracts() = lazy {
      val clazz: Class&lt;ViewModel&gt; = arguments?.getSerializable(VM_KEY) as Class&lt;ViewModel&gt;
      val viewModelProvider = ViewModelProvider(requireActivity())
  
      return@lazy viewModelProvider.get(clazz) as T
  }
  </code></pre>
  <p>The <code>ViewModelStoreOwner</code> passed as parameter is an <code>Activity</code>, but if I have a <code>Fragment</code> inside another <code>Fragment</code> where both of them share the same <code>ViewModel</code>, the <code>ViewModel</code> returned by <code>viewModelContracts()</code> will be a different object as the one created by the Parent <code>Fragment</code>.</p>
  <pre><code>interface ChildViewModelContract {
      // ...
  }
  
  class SomeViewModel : ViewModel(), ChildViewModelContract {
      // ...
  }
  
  class ParentFragment: Fragment {
      private val viewModel: SomeViewModel by viewModels()
  
      // ...
  }
  
  class ChildFragment: Fragment {
      private val viewModelContract: ChildViewModelContract by viewModelContracts()
  
      // ...
  }
  </code></pre>
  <p>The ideal solution would be to check in <code>fun &lt;T&gt; Fragment.viewModelContracts()</code> if the <code>ViewModelProvider</code> of the parent fragment has the <code>ViewModel</code> stored in it, and if not, use the <code>ViewModelProvider</code> of the Activity. But I'm not knowing how to do this.</p>
  <pre><code>fun &lt;T&gt; Fragment.viewModelContracts() = lazy {
      val clazz: Class&lt;ViewModel&gt; = arguments?.getSerializable(VM_KEY) as Class&lt;ViewModel&gt;
      
      val parentFragment = parentFragment
      if (parentFragment != null) {
          val viewModelProvider = ViewModelProvider(parentFragment)
          // is there any way to do something like this?
          if (viewModelProvider.isViewModelStored(clazz)) {
              return@lazy viewModelProvider.get(clazz) as T 
          }
      }
      
      val viewModelProvider = ViewModelProvider(requireActivity())
      
      return@lazy viewModelProvider.get(clazz) as T
  }
  </code></pre>