Kotlin Flow: How to unsubscribe/stop

A solution is not to cancel the flow, but the Job returned from launching the flow in a scope.

val job = scope.launch { flow.cancellable().collect { } }
job.cancel()

NOTE: cancellable() will ensure the flow is terminated before new items are emitted to collect { } if its job is cancelled, though flow builder and all implementations of SharedFlow are cancellable() by default.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)