Skip to content

Instantly share code, notes, and snippets.

View mayojava's full-sized avatar

Mayowa Adegeye mayojava

View GitHub Profile
@mayojava
mayojava / coroutine_parent_child.kt
Last active October 26, 2018 10:42
coroutine parent child relationship
fun main() = runBlocking<Unit>{
launch(Dispatchers.Default) {
repeat(5) {
println("coroutine 1: $it")
delay(500)
}
}
launch(Dispatchers.Default) {
repeat(5) {
println("coroutine 2: $it")
fun main() = runBlocking {
val startTime = System.currentTimeMillis()
val job = launch(Dispatchers.Default) {
var nextPrintTime = startTime
var i = 0
while (i < 5) { // computation loop, just wastes CPU
// print a message twice a second
if (System.currentTimeMillis() >= nextPrintTime) {
println("I'm sleeping ${i++} ...")
nextPrintTime += 500L
fun main(args: Array<String>) = runBlocking<Unit> {
val job = launch {
repeat(10) {
println("hello")
delay(500)
}
}
delay(2000) // delays for launched coroutine to run for a while
println("cancelling")
@mayojava
mayojava / coroutine_observer.kt
Created October 26, 2018 07:59
Corotuine Observer
class CoroutineObserver: LifecycleObserver, CoroutineScope {
private lateinit var job: Job
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Default
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() {
job = Job()
}
suspend fun backgroundTask(param: Int): Int {
// long running operation
}
fun backgroundTask(param: Int, callback: Continuation<Int>): Int {
// long running operation
}
interface Continuation<in T> {
val context: CoroutineContext
fun resume(value: T)
fun resumeWithException(exception: Throwable)
}
fun main(args: Array<String>) = runBlocking<Unit> {
launch(Dispatchers.Unconfined) {
println("current thread: ${Thread.currentThread().name}")
delay(1_000)
println("current thread: ${Thread.currentThread().name}")
}
}
//prints
current thread: main
current thread: kotlinx.coroutines.DefaultExecutor
fun CoroutineScope.launch(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> Unit
): Job
fun main(args: Array<String>) = runBlocking {
val time = measureTimeMillis {
val first = async { firstNumber() }
val second = async { secondNumber() }
val third = async { thirdNumber() }
val result = first.await() + second.await() + third.await()
}
println(time) //prints 7 seconds