aboutsummaryrefslogtreecommitdiff
path: root/app/src/main/kotlin/com/pitchedapps/frost/kotlin/CoroutineUtils.kt
blob: 0e09968d455fa7db01f22467d47455e4cc45a894 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.pitchedapps.frost.kotlin

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.BroadcastChannel
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext

@UseExperimental(ExperimentalCoroutinesApi::class)
fun <T> BroadcastChannel<T>.subscribeDuringJob(
    scope: CoroutineScope,
    context: CoroutineContext,
    onReceive: suspend (T) -> Unit
) {
    val receiver = openSubscription()
    scope.launch(context) {
        for (r in receiver) {
            onReceive(r)
        }
    }
    scope.coroutineContext[Job]!!.invokeOnCompletion { receiver.cancel() }
}