From ddfd17de81d143aef83a421c57867d42ddc7ff9b Mon Sep 17 00:00:00 2001 From: Alexander Nozik Date: Fri, 5 Mar 2021 10:54:18 +0300 Subject: [PATCH] coroutine demo --- build.gradle.kts | 11 +++++--- src/main/kotlin/demos/coroutineDemo.kt | 36 ++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 3 deletions(-) create mode 100644 src/main/kotlin/demos/coroutineDemo.kt diff --git a/build.gradle.kts b/build.gradle.kts index 5931ffb..bb10686 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,5 +1,3 @@ -import org.jetbrains.kotlin.gradle.tasks.KotlinCompile - plugins { kotlin("jvm") version "1.4.30" } @@ -7,20 +5,27 @@ plugins { group = "ru.mipt.npm" version = "1.0" +// Where to get dependencies repositories { mavenCentral() } dependencies { + //loading coroutines + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.3") + + //testing libraries testImplementation(kotlin("test-junit5")) testImplementation("org.junit.jupiter:junit-jupiter-api:5.6.0") testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.6.0") } +// Load testing platform tasks.test { useJUnitPlatform() } -tasks.withType() { +// Set a byte-code target for JVM +tasks.withType { kotlinOptions.jvmTarget = "11" } \ No newline at end of file diff --git a/src/main/kotlin/demos/coroutineDemo.kt b/src/main/kotlin/demos/coroutineDemo.kt new file mode 100644 index 0000000..c77375e --- /dev/null +++ b/src/main/kotlin/demos/coroutineDemo.kt @@ -0,0 +1,36 @@ +package demos + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch + +suspend fun doASuspendedThing() { + delay(500) +} + +suspend fun doASuspendedThingWithResult(): Int { + delay(500) + return 4 +} + +suspend fun main() { + //sequential coroutine + GlobalScope.launch { + doASuspendedThingWithResult() + // do a thing and do next thing when the result is there without blocking + doASuspendedThing() + } + + //parallel coroutines + GlobalScope.launch(Dispatchers.Default) { + val job1 = launch { + doASuspendedThing() + } + val job2 = launch { + doASuspendedThing() + } + job1.join() + job2.join() + } +} \ No newline at end of file