title: How to write a coroutine function in BaseViewModel that can be used in child ViewModel
body: <p>I write a BaseViewModel below</p>
  <pre><code>open class BaseViewModel : ViewModel() {
  
      private val coroutinesScope = CoroutineScope(Dispatchers.Default + Job())
      val errorMessage: MutableLiveData&lt;String&gt; = MutableLiveData()
  }
  </code></pre>
  <p>use child viewModel extend it and it works.</p>
  <p>(<code>getUserProfile()</code> is a suspend function)</p>
  <pre><code>class AAA : BaseViewModel() {
  
      fun getUserProfile() {
  
          coroutinesScope.launch {
              try {
                  ApiService.Account.getUserProfile().let { profile -&gt;// works
                      if (profile.success) {
  
                      }
                  }
              } catch (e: Exception) {
                  errorMessage.postValue(Constant.System_error)
              }
          }
      }
  }
  </code></pre>
  <p>and i want to move <code>coroutinesScope.launch</code> into BaseViewModel
  so i write the <code>launch</code> function</p>
  <pre><code>open class BaseViewModel : ViewModel() {
  
      val coroutinesScope = CoroutineScope(Dispatchers.Default + Job())
      val errorMessage: MutableLiveData&lt;String&gt; = MutableLiveData()
  
      fun launch(function: () -&gt; Unit) {
          coroutinesScope.launch {
              try {
                  function.invoke()
              } catch (e: Exception) {
                  errorMessage.postValue(Constant.System_error)
              }
          }
      }
  }
  </code></pre>
  <p>Getting error <code>suspend function can only be called within coroutine body</code></p>
  <pre><code>class AAA : BaseViewModel() {
  
      fun getUserProfile() {
  
          launch {
  
              ApiService.Account.getUserProfile().let { profile -&gt;// getting compile error
                  if (profile.success) {
  
                  }
              }
          }
      }
  }
  </code></pre>
  <p>how to solve it, thanks.</p>