title: Kotlin Flow: unsubscribe from SharedFlow when Fragment becomes invisible
body: <p>I've read similar topics but couldn't find a proper answer:</p>
  <ul>
  <li><a href="https://stackoverflow.com/questions/64372517/how-to-end-close-a-mutablesharedflow">How to end / close a MutableSharedFlow?</a></li>
  <li><a href="https://stackoverflow.com/questions/57088428/kotlin-flow-how-to-unsubscribe-stop/64785132#64785132">Kotlin Flow: How to unsubscribe/stop</a></li>
  <li><a href="https://developer.android.com/kotlin/flow/stateflow-and-sharedflow#sharein" rel="nofollow noreferrer">StateFlow and SharedFlow. Making cold flows hot using shareIn</a> - Android docs</li>
  <li><a href="https://github.com/Kotlin/kotlinx.coroutines/issues/2034" rel="nofollow noreferrer">Introduce SharedFlow</a> - GH discussion started by Roman Elizarov</li>
  </ul>
  <p>In my <code>Repository</code> class I have a cold <code>Flow</code> that I want to share to 2 <code>Presenters</code>/<code>ViewModels</code> so my choice is to use <code>shareIn</code> operator.</p>
  <p>Let's take a look on Android docs' example:</p>
  <pre><code>val latestNews: Flow&lt;List&lt;ArticleHeadline&gt;&gt; = flow {
      ...
  }.shareIn(
      externalScope,  // e.g. CoroutineScope(Dispatchers.IO)?
      replay = 1,
      started = SharingStarted.WhileSubscribed()
  )
  </code></pre>
  <p>What docs suggests for <code>externalScope</code> parameter:</p>
  <blockquote>
  <p>A CoroutineScope that is used to share the flow. This scope should live longer than any consumer to keep the shared flow alive as long as needed.</p>
  </blockquote>
  <p>However, looking for answer on how to stop subscribing a <code>Flow</code>, the most voted answer in 2nd link says:</p>
  <blockquote>
  <p>A solution is not to cancel the flow, but the scope it's launched in.</p>
  </blockquote>
  <p>For me, these answers are contradictory in <code>SharedFlow</code>'s case. And unfortunately my <code>Presenter</code>/<code>ViewModel</code> still receives newest data even after its <code>onCleared</code> was called.</p>
  <p>How to prevent that? This is an example how I consume this <code>Flow</code> in my <code>Presenter</code>/<code>ViewModel</code>:</p>
  <pre><code>fun doSomethingUseful(): Flow&lt;OtherModel&gt; {
      return repository.latestNews.map(OtherModel)
  </code></pre>
  <p>If this might help, I'm using MVI architecture so <code>doSomethingUseful</code> reacts to some intents created by the user.</p>