title: Deallocating LiveData when inactive
body: <p>Some background info: I am developing an application that relies on Architecture Components to pass data between layers, and using the MVVM architecture.</p>
  
  <p>My repositories have a number of functions that return LiveDatas and are observed by the ViewModel via Transformations, and then by the Views and their Lifecycles.</p>
  
  <p>What I noticed is that when an Activity is stopped, the observer is removed, but the repository function that provided the original LiveData stays in memory. Furthermore, when a new request is made, a completely new object is created, so the memory keeps increasing.</p>
  
  <p>The entire GitHub repo is at <a href="https://github.com/EmilioSchepis/QRSync" rel="nofollow noreferrer">this link</a>, and specifically one of the functions is</p>
  
  <pre><code>override fun retrieveCode(id: String):
          LiveData&lt;Either&lt;QSError, QSCode&gt;&gt; {
      val codeReference = codesReference.document(id)
      val observable = MutableLiveData&lt;Either&lt;QSError, QSCode&gt;&gt;()
  
      codeReference.addSnapshotListener { snapshot, exception -&gt;
          if (exception != null) {
              // An error occurred.
              val error = QSError.fromException(exception)
              observable.postValue(error.left())
          } else {
              // The detail must not be null, that would
              // mean that the code was not found.
              val detail = snapshot?.toObject(QSCode::class.java)
              if (snapshot == null || detail == null) {
                  observable.postValue(QSError.DatabaseError.NotFound.left())
              } else {
                  observable.postValue(detail.right())
              }
          }
      }
      return observable
  }
  </code></pre>
  
  <p>I understand that the function creates a new MutableLiveData each time it is called, but I can't figure out how to make it return the same one, or at the very least clean up the old one first.</p>
  
  <p>Here are a few screenshots of the Android Profiler showing the duplicated instances. <a href="https://i.stack.imgur.com/ljTB8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ljTB8.png" alt="Screenshot of a duplicated instance"></a><a href="https://i.stack.imgur.com/2W1xJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2W1xJ.png" alt="Screenshot 2 of a duplicated instance"></a></p>
  
  <p>In this particular case, the <code>retrieveCode</code> is called twice. Not only the function generates two separate LiveDatas, it generates two for each call.</p>
  
  <p>What am I missing? It might be a very trivial problem. </p>
  
  <p>Thank you.</p>
  
  <p>==========</p>
  
  <p>EDIT: This is exactly how the <a href="https://developer.android.com/jetpack/docs/guide#fetching_data" rel="nofollow noreferrer">Guide to App Architecture</a> does it.</p>