title: How to cancel a running LiveData Coroutine Block
body: <p>By using LiveData's latest version "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0-alpha03", I have developed a code for a feature called "Search Products" in the ViewModel using LiveData's new building block (LiveData + Coroutine) that performs a synchronous network call using Retrofit and update different flags (isLoading, isError) in ViewModel accordingly. I am using Transforamtions.switchMap on "query" LiveData so whenever there is a change in "query" from the UI, the "Search Products" code starts its executing using Transformations.switchMap. Every thing is working fine, except that i want to cancel the previous Retrofit Call whenever a change happens in "query" LiveData. Currently i can't see any way to do this. Any help would be appreciated. </p>
  
  <pre><code>class ProductSearchViewModel : ViewModel() {
      val completableJob = Job()
      private val coroutineScope = CoroutineScope(Dispatchers.IO + completableJob)
  
      // Query Observable Field
      val query: MutableLiveData&lt;String&gt; = MutableLiveData()
  
      // IsLoading Observable Field
      private val _isLoading = MutableLiveData&lt;Boolean&gt;()
      val isLoading: LiveData&lt;Boolean&gt; = _isLoading
  
  
      val products: LiveData&lt;List&lt;ProductModel&gt;&gt; = query.switchMap { q -&gt;
          liveData(context = coroutineScope.coroutineContext) {
              emit(emptyList())
              _isLoading.postValue(true)
              val service = MyApplication.getRetrofitService()
              val response = service?.searchProducts(q)
              if (response != null &amp;&amp; response.isSuccessful &amp;&amp; response.body() != null) {
                  _isLoading.postValue(false)
                  val body = response.body()
                  if (body != null &amp;&amp; body.results != null) {
                      emit(body.results)
                  }
              } else {
                  _isLoading.postValue(false)
              }
          }
      }
  }
  </code></pre>