title: How to make viewModelScope wait for a suspend function in unit test
body: <p>As we know the default dispatcher for viewModelScope executes in parallel. How do I make viewModelScope wait for the suspend function in unit test . In my code i would like to get the result from <code>repository.getData()</code> so that my assertion passes. Right now, i don't get the result on time. </p>
  
  <pre><code>class MainViewModel(private val repository: Repository,
                       private val dispatcher: CoroutineDispatcherProvider) : ViewModel() {
  
      private val viewState = MutableLiveData&lt;Results&lt;Data&gt;&gt;()
      fun getViewState() : LiveData&lt;Results&lt;Data&gt;&gt; = viewState
  
  
  
      fun getData(query: search) {
          viewState.value = Loading
          viewModelScope.launch(dispatcher.main()) {
              val results = repository.getData(query) //need to wait for this
              when(results){
                      is Success -&gt; {
                          viewState.value = Success(results.data)
                      }
                      is Error -&gt; viewState.value = Error(“Error”)
                  }
          }
  </code></pre>
  
  <p>MainViewModelTest:</p>
  
  <pre><code> Class MainViewModelTest {
  
      @get:Rule
      val instantExecutorRule = InstantTaskExecutorRule()
  
      @get:Rule
      val coroutineTestRule = CoroutineTestRule()
  
  
      @Test
      fun `test get data`() = coroutineTestRule.testCoroutineDispatcher.runBlockingTest {
          coEvery{repository.getData(“query”)} returns Success(Data)
  
          var observer:Observer&lt;Results&lt;Data&gt;&gt; = mock()
  
          viewModel.getViewState().observeForever(observer)
  
          viewModel.getData(“query”)
  
            assertEquals(Loading, state)
            assertEquals(resultSuccess, state)
  
         }
  
      }
  </code></pre>