Skip to content

Instantly share code, notes, and snippets.

@dave08
Last active March 15, 2018 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dave08/0cbbc5545732e280109ebffbe497ec7d to your computer and use it in GitHub Desktop.
Save dave08/0cbbc5545732e280109ebffbe497ec7d to your computer and use it in GitHub Desktop.
import kotlinx.coroutines.experimental.*
import kotlinx.coroutines.experimental.channels.*
import org.junit.Test
import kotlin.coroutines.experimental.CoroutineContext
data class Intent(val action: String)
class BroadcastSender() {
}
interface BroadcastReceiver {
fun onReceive(intent: Intent)
}
class Context() {
var broadcastReceiver: BroadcastReceiver? = null
fun send(action: String) { broadcastReceiver?.onReceive(Intent(action)) }
fun registerReceiver(broadcastReceiver: BroadcastReceiver) {
this.broadcastReceiver = broadcastReceiver
}
fun unregisterReceiver(broadcastReceiver: BroadcastReceiver) {
this.broadcastReceiver = null
}
}
suspend fun awaitCancel(): Nothing = suspendCancellableCoroutine { }
suspend fun registerBroadcastReceiver(context: Context): ReceiveChannel<Intent> =
produce<Intent>(capacity = Channel.UNLIMITED) {
var broadcastReceiver:BroadcastReceiver? = null
try {
broadcastReceiver = object : BroadcastReceiver {
override fun onReceive(intent: Intent) {
sendBlocking(intent)
}
}.also {
context.registerReceiver(it)
awaitCancel()
}
} finally {
context.unregisterReceiver(broadcastReceiver!!)
}
}
class CoroutineTest {
@Test
fun testProduceCallbackWrapper() = runBlocking {
val context = Context()
val channel = registerBroadcastReceiver(context)
val result = async(coroutineContext) { channel.any {
if (it.action == "hello") { channel.cancel(); true } else false
} }
context.send("hello")
yield()
assert(result.await())
}
@Test
fun testProduceCallbackWrapperWithFor() = runBlocking {
val context = Context()
val channel = registerBroadcastReceiver(context)
var result = false
launch(coroutineContext) {
for (currIntent in channel) {
if(currIntent.action == "hello") {
result = true
channel.cancel()
}
}
}
context.send("something1")
context.send("something2")
context.send("something3")
context.send("something4")
context.send("hello")
yield()
assert(result)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment