2

I can launch my stateFlow collection as below

val collectingScope = CoroutineScope(Dispatchers.Default)
val stateFlow = MutableStateFlow(0)

val myJob =  collectingScope.launch {
        stateFlow.collect {
            println("collected $it")
        }
    }

And I can cancel it using

myJob.cancel()

But I wonder if I can also cancel it through the stateFlow instead? I see there's a cancel() function but it's deprecated

@Deprecated(
    message = "cancel() is resolved into the extension of outer CoroutineScope which is likely to be an error." +
        "Use currentCoroutineContext().cancel() instead or specify the receiver of cancel() explicitly",
    level = DeprecationLevel.ERROR,
    replaceWith = ReplaceWith("currentCoroutineContext().cancel(cause)")
)
public fun FlowCollector<*>.cancel(cause: CancellationException? = null): Unit = noImpl()

If I can do so, does the cancelation also auto-cancel myJob?

Elye
  • 53,639
  • 54
  • 212
  • 474

1 Answers1

0

No. StateFlows cannot be cancelled. See the documentation:

State flow never completes. A call to Flow.collect on a state flow never completes normally, and neither does a coroutine started by the Flow.launchIn function. An active collector of a state flow is called a subscriber.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413