https://kotlinlang.org logo
Title
d

dave08

03/15/2018, 11:49 AM
We have a use case like this:
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

elizarov

03/15/2018, 1:05 PM
Just suspend the
produce
indefinitely.
suspendCancellableCoroutine {}
. That is your wait for cancellation