We have a use case like this: ```fun registerBroad...
# coroutines
d
We have a use case like this:
Copy code
fun registerBroadcastReceiver(context: Context, intentFilter: IntentFilter): ReceiveChannel<Intent> =
        produce(capacity = Channel.UNLIMITED) {
            var broadcastReceiver:BroadcastReceiver? = null
            try {
                broadcastReceiver = object : BroadcastReceiver() {
                    override fun onReceive(context: Context, intent: Intent) {
                        offer(intent)
                    }
                }.also { context.registerReceiver(it, intentFilter) }
            } catch(e: CancellationException) {
                context.unregisterReceiver(broadcastReceiver)
            }
        }
But with this the Channel is obviously closed right away... How could we implement this otherwise? We don't want the user of the function to have to unregister the receiver, but rather that when the channel is cancelled, it should automatically be unregistered...
e
Just suspend the
produce
indefinitely.
suspendCancellableCoroutine {}
. That is your wait for cancellation