Skip to content

Instantly share code, notes, and snippets.

View mayojava's full-sized avatar

Mayowa Adegeye mayojava

View GitHub Profile
@mayojava
mayojava / conflated_channel.kt
Created November 7, 2018 18:52
Conflated BroadcastChannel
fun main() = runBlocking<Unit> {
val channel = ConflatedBroadcastChannel<Int>()
launch {
channel.consumeEach {
println("first: $it")
delay(500)
}
}
@mayojava
mayojava / channel_consumed_once.kt
Created November 7, 2018 18:47
Consuming a channel once
fun main() = runBlocking {
val channel = Channel<Int>()
launch {
repeat(5) {
channel.send(it*it)
}
channel.close()
}
println("begin")
@mayojava
mayojava / channel_receive.kt
Created November 7, 2018 18:45
Receiving from a channel
fun main() = runBlocking<Unit> {
val channel = Channel<Int>()
launch {
for (i in 1..5) {
channel.send(i)
}
channel.close()
}
val channel = Channel<ItemType>(bufferSize)
@mayojava
mayojava / channel_interface.kt
Created November 7, 2018 18:43
Send and Receive channel interfaces
interface SendChannel<in E> {
public suspend fun send(element: E)
public fun offer(element: E): Boolean
public fun close(cause: Throwable? = null): Boolean
}
interface ReceiveChannel<out E> {
public suspend fun receive(): E
public fun poll(): E?
public fun cancel()
@mayojava
mayojava / cancellation_check.kt
Created October 26, 2018 10:36
Check for coroutine cancellation
while (isActive) {
// print a message twice a second
if (System.currentTimeMillis() >= nextPrintTime) {
println("I'm sleeping ${i++} ...")
nextPrintTime += 500L
}
}
@mayojava
mayojava / android_activity.kt
Created October 26, 2018 10:33
Android Activity implementing CoroutineScope
class MainActivity: AppCompatActivity(), CoroutineScope {
lateinit var job: Job
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
job = Job()
}
@mayojava
mayojava / supervisor.kt
Created October 26, 2018 10:29
Supervisor scope
fun main() = runBlocking<Unit> {
launchChildren()
println("body of main")
}
suspend fun launchChildren() = supervisorScope {
launch(Dispatchers.Default) {
repeat(5) {
println("coroutine 1: count $it")
if(it == 2) {
@mayojava
mayojava / custom_coroutine_scope.kt
Last active October 26, 2018 10:28
Custom Coroutine Scope
fun main() = runBlocking{
launchChildren()
println("never gets printed") // this line never gets printed
}
suspend fun launchChildren(): Int = coroutineScope {
val first = async {
try {
firstValue()
} finally {
@mayojava
mayojava / non_cancellable.kt
Created October 26, 2018 10:25
Non cancallable code
fun main() = runBlocking<Unit>{
launch {
withContext(NonCancellable) {
repeat(5) {
println("count: $it")
delay(500)
}
}
}