title: Kotlin Coroutines wait for job to complete
body: <p>I have a ViewModel. Inside it, I have a function which fetches some images from the phones internal storage. </p>
  
  <p>Before the fetching is complete it is exposing livedata in mainactivity. How to make coroutines to wait for the task to complete and expose the live data.</p>
  
  <pre><code> // This is my ViewModel
  
   private val _image = MutableLiveData&lt;ArrayList&lt;File&gt;&gt;()
   val images: LiveData&lt;ArrayList&lt;File&gt;&gt; get() = _image
  
  fun fetchImage(){
      val file = Path.imageDirectory  //  returns a directory where images are stored
      val files = arrayListOf&lt;File&gt;()
      viewModelScope.launch {
          withContext(Dispatchers.IO) {
              if (file.exists()) {
                  file.walk().forEach {
                      if (it.isFile &amp;&amp; it.path.endsWith("jpeg")) {
                          files.add(it)
                      }
                  }
              }
  
              files.sortByDescending { it.lastModified() } // sort the files to get newest 
                                                           // ones at top of the list
          }
      }
  
      _image.postValue(files)
  }
  </code></pre>
  
  <p>Is there any other approach to make this code much faster by any other methods? </p>