Skip to content

Instantly share code, notes, and snippets.

@Audhil
Created October 27, 2017 19: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 Audhil/ce7299f0888ae8363f66c927603f0d12 to your computer and use it in GitHub Desktop.
Save Audhil/ce7299f0888ae8363f66c927603f0d12 to your computer and use it in GitHub Desktop.
Kotlin coroutine's demo
package com.example.demo
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.coroutines.experimental.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// coroutineDemo()
// runBlockingDemo()
// doWorksInSeries()
// doWorksInParallel()
}
// #2
fun runBlockingDemo() {
runBlocking {
delay(2000)
println("Kotlin inside coroutines")
}
}
// The output will be
// Kotlin inside coroutines
// #1
fun coroutineDemo() {
println("Kotlin Start")
launch(CommonPool) {
delay(2000)
println("Kotlin Inside")
}
println("Kotlin End")
}
// The output will be
// Kotlin Start
// Kotlin End
// Kotlin Inside
suspend fun doWorkFor1Seconds(): String {
delay(1000)
return "doWorkFor1Seconds"
}
suspend fun doWorkFor2Seconds(): String {
delay(2000)
return "doWorkFor2Seconds"
}
// #3
// Serial execution
fun doWorksInSeries() {
launch(CommonPool) {
val one = doWorkFor1Seconds()
val two = doWorkFor2Seconds()
println("Kotlin One : " + one)
println("Kotlin Two : " + two)
}
}
// The output is
// Kotlin One : doWorkFor1Seconds
// Kotlin Two : doWorkFor2Seconds
// #4
// Parallel execution
private fun doWorksInParallel() {
val one = async(CommonPool) {
doWorkFor1Seconds()
}
val two = async(CommonPool) {
doWorkFor2Seconds()
}
launch(CommonPool) {
val combined = one.await() + "_" + two.await()
println("Kotlin Combined : " + combined)
}
}
// The output is
// Kotlin Combined : doWorkFor1Seconds_doWorkFor2Seconds
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment