Skip to content

Commit 1d1cf6e

Browse files
authored
Coroutines source code of Youtube videos
1 parent 0570120 commit 1d1cf6e

19 files changed

+420
-0
lines changed

src/60_thread_example.kt

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import kotlin.concurrent.thread
2+
3+
fun main() { // Executes in main thread
4+
5+
println("Main program starts: ${Thread.currentThread().name}")
6+
7+
thread { // creates a background thread (worker thread)
8+
println("Fake work starts: ${Thread.currentThread().name}")
9+
Thread.sleep(1000) // Pretend doing some work... may be file upload
10+
println("Fake work finished: ${Thread.currentThread().name}")
11+
}
12+
13+
println("Main program ends: ${Thread.currentThread().name}")
14+
}

src/61_first_coroutine.kt

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import kotlinx.coroutines.*
2+
3+
4+
fun main() { // Executes in main thread
5+
6+
println("Main program starts: ${Thread.currentThread().name}")
7+
8+
GlobalScope.launch { // creates a background coroutine that runs on a background thread
9+
println("Fake work starts: ${Thread.currentThread().name}")
10+
Thread.sleep(1000) // Pretend doing some work... may be file upload
11+
println("Fake work finished: ${Thread.currentThread().name}")
12+
}
13+
14+
// Blocks the current main thread & wait for coroutine to finish (practically not a right way to wait)
15+
Thread.sleep(2000)
16+
println("Main program ends: ${Thread.currentThread().name}")
17+
}

src/62_runBlocking_and_delay.kt

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import kotlinx.coroutines.*
2+
3+
4+
fun main() = runBlocking { // Executes in main thread
5+
6+
println("Main program starts: ${Thread.currentThread().name}") // main thread
7+
8+
GlobalScope.launch { // Thread: T1
9+
println("Fake work starts: ${Thread.currentThread().name}") // Thread: T1
10+
delay(1000) // Coroutine is suspended but Thread: T1 is free (not blocked)
11+
println("Fake work finished: ${Thread.currentThread().name}") // Either T1 or some other thread.
12+
}
13+
14+
delay(2000) // main thread: wait for coroutine to finish (practically not a right way to wait)
15+
16+
println("Main program ends: ${Thread.currentThread().name}") // main thread
17+
}

src/63_custom_suspending_function.kt

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
2+
import kotlinx.coroutines.*
3+
4+
5+
fun main() = runBlocking { // Executes in main thread
6+
7+
println("Main program starts: ${Thread.currentThread().name}") // main thread
8+
9+
GlobalScope.launch { // Thread: T1
10+
println("Fake work starts: ${Thread.currentThread().name}") // Thread: T1
11+
mySuspendFunc(1000) // Coroutine is suspended but Thread: T1 is free (not blocked)
12+
println("Fake work finished: ${Thread.currentThread().name}") // Either T1 or some other thread.
13+
}
14+
15+
mySuspendFunc(2000) // main thread: wait for coroutine to finish (practically not a right way to wait)
16+
17+
println("Main program ends: ${Thread.currentThread().name}") // main thread
18+
}
19+
20+
suspend fun mySuspendFunc(time: Long) {
21+
// code..
22+
delay(time)
23+
}

src/64_launch_coroutine_builder.kt

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import kotlinx.coroutines.*
2+
3+
4+
fun main() = runBlocking { // Creates a blocking coroutine that executes in current thread (main)
5+
6+
println("Main program starts: ${Thread.currentThread().name}") // main thread
7+
8+
val job: Job = launch { // Thread: main
9+
println("Fake work starts: ${Thread.currentThread().name}") // Thread: main
10+
delay(1000) // Coroutine is suspended but Thread: main is free (not blocked)
11+
println("Fake work finished: ${Thread.currentThread().name}") // Thread: main
12+
}
13+
14+
job.join() // main thread: wait for coroutine to finish
15+
16+
println("Main program ends: ${Thread.currentThread().name}") // main thread
17+
}

src/65_async_coroutine_builder.kt

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import kotlinx.coroutines.*
2+
3+
4+
fun main() = runBlocking { // Creates a blocking coroutine that executes in current thread (main)
5+
6+
println("Main program starts: ${Thread.currentThread().name}") // main thread
7+
8+
val deferredJob: Deferred<Unit> = async // Thread: main
9+
println("Fake work starts: ${Thread.currentThread().name}") // Thread: main
10+
delay(1000) // Coroutine is suspended but Thread: main is free (not blocked)
11+
println("Fake work finished: ${Thread.currentThread().name}") // Thread: main
12+
15
13+
}
14+
15+
val num: Int = deferredJob.await() // main thread: wait for coroutine to finish and return data
16+
17+
println("Main program ends: ${Thread.currentThread().name}") // main thread
18+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import kotlinx.coroutines.*
2+
3+
4+
fun main() = runBlocking { // Creates a blocking coroutine that executes in current thread (main)
5+
6+
println("Main program starts: ${Thread.currentThread().name}") // main thread
7+
8+
val deferredJob: Deferred<Unit> = async // Thread: main
9+
println("Fake work starts: ${Thread.currentThread().name}") // Thread: main
10+
delay(1000) // Coroutine is suspended but Thread: main is free (not blocked)
11+
println("Fake work finished: ${Thread.currentThread().name}") // Thread: main
12+
15
13+
}
14+
15+
val num: Int = deferredJob.await() // main thread: wait for coroutine to finish and return data
16+
17+
println("Main program ends: ${Thread.currentThread().name}") // main thread
18+
}
19+
20+
suspend fun myOwnSuspendingFunc() {
21+
delay(1000) // do something
22+
}

src/66_b_test_case.kt

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import kotlinx.coroutines.runBlocking
2+
import org.junit.Assert
3+
import org.junit.Test
4+
5+
class SimpleTest {
6+
7+
@Test
8+
fun myFirstTest() = runBlocking {
9+
myOwnSuspendingFunc()
10+
Assert.assertEquals(10, 5 + 5)
11+
}
12+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import kotlinx.coroutines.*
2+
3+
fun main() = runBlocking { // Creates a blocking coroutine that executes in current thread (main)
4+
5+
println("Main program starts: ${Thread.currentThread().name}") // main thread
6+
7+
val job: Job = launch { // Thread T1: Creates a non-blocking coroutine
8+
for (i in 0..500) {
9+
print("$i.")
10+
yield() // or use delay() or any other suspending function as per your need.
11+
}
12+
}
13+
14+
delay(10) // Let's print a few values before we cancel
15+
job.cancelAndJoin()
16+
17+
println("\nMain program ends: ${Thread.currentThread().name}") // main thread
18+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import kotlinx.coroutines.*
2+
3+
fun main() = runBlocking { // Creates a blocking coroutine that executes in current thread (main)
4+
5+
println("Main program starts: ${Thread.currentThread().name}") // main thread
6+
7+
val job: Job = launch(Dispatchers.Default) { // Thread T1: Creates a non-blocking coroutine
8+
for (i in 0..500) {
9+
if (!isActive) {
10+
return@launch // break
11+
}
12+
print("$i.")
13+
Thread.sleep(1)
14+
}
15+
}
16+
17+
delay(10) // Let's print a few values before we cancel
18+
job.cancelAndJoin()
19+
20+
println("\nMain program ends: ${Thread.currentThread().name}") // main thread
21+
}

src/70_exception_handling.kt

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import kotlinx.coroutines.*
2+
3+
fun main() = runBlocking { // Creates a blocking coroutine that executes in current thread (main)
4+
5+
println("Main program starts: ${Thread.currentThread().name}") // main thread
6+
7+
val job: Job = launch(Dispatchers.Default) { // Thread T1: Creates a non-blocking coroutine
8+
try {
9+
for (i in 0..500) {
10+
print("$i.")
11+
delay(5) // or use yield() or any other suspending function as per your need.
12+
}
13+
} catch (ex: CancellationException) {
14+
print("\nException caught safely: ${ex.message}")
15+
} finally {
16+
print("\nClose resources in finally")
17+
}
18+
}
19+
20+
delay(10) // Let's print a few values before we cancel
21+
job.cancel(CancellationException("My own crash message"))
22+
job.join()
23+
24+
println("\nMain program ends: ${Thread.currentThread().name}") // main thread
25+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import kotlinx.coroutines.*
2+
3+
fun main() = runBlocking { // Creates a blocking coroutine that executes in current thread (main)
4+
5+
println("Main program starts: ${Thread.currentThread().name}") // main thread
6+
7+
val job: Job = launch(Dispatchers.Default) { // Thread T1: Creates a non-blocking coroutine
8+
try {
9+
for (i in 0..500) {
10+
print("$i.")
11+
delay(5) // or use yield() or any other suspending function as per your need.
12+
}
13+
} catch (ex: CancellationException) {
14+
print("\nException caught safely: ${ex.message}")
15+
} finally {
16+
withContext(NonCancellable) {
17+
delay(1000) // Generally we don't use suspending function in finally
18+
print("\nClose resources in finally")
19+
}
20+
}
21+
}
22+
23+
delay(10) // Let's print a few values before we cancel
24+
job.cancel(CancellationException("My own crash message"))
25+
job.join()
26+
27+
println("\nMain program ends: ${Thread.currentThread().name}") // main thread
28+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import kotlinx.coroutines.*
2+
3+
fun main() = runBlocking { // Creates a blocking coroutine that executes in current thread (main)
4+
5+
println("Main program starts: ${Thread.currentThread().name}") // main thread
6+
7+
withTimeout(1300) {
8+
try {
9+
for (i in 0..1000) {
10+
print("$i.")
11+
delay(500)
12+
}
13+
} catch (ex: TimeoutCancellationException) {
14+
// .. code..
15+
} finally {
16+
// .. code..
17+
}
18+
}
19+
20+
println("\nMain program ends: ${Thread.currentThread().name}") // main thread
21+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import kotlinx.coroutines.*
2+
3+
fun main() = runBlocking { // Creates a blocking coroutine that executes in current thread (main)
4+
5+
println("Main program starts: ${Thread.currentThread().name}") // main thread
6+
7+
val result: String? = withTimeoutOrNull(2000) {
8+
for (i in 0..500) {
9+
print("$i.")
10+
delay(500)
11+
}
12+
13+
"I am done"
14+
}
15+
16+
print("Result: $result")
17+
18+
println("\nMain program ends: ${Thread.currentThread().name}") // main thread
19+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import kotlinx.coroutines.*
2+
import kotlin.system.measureTimeMillis
3+
4+
5+
fun main() = runBlocking { // Creates a blocking coroutine that executes in current thread (main)
6+
7+
println("Main program starts: ${Thread.currentThread().name}") // main thread
8+
9+
val time = measureTimeMillis {
10+
val msgOne = getMessageOne()
11+
val msgTwo = getMessageTwo()
12+
println("The entire message is: ${msgOne + msgTwo}")
13+
}
14+
15+
println("Completed in $time ms")
16+
println("Main program ends: ${Thread.currentThread().name}") // main thread
17+
}
18+
19+
suspend fun getMessageOne(): String {
20+
delay(1000L) // pretend to do some work
21+
return "Hello "
22+
}
23+
24+
suspend fun getMessageTwo(): String {
25+
delay(1000L) // pretend to do some work
26+
return "World!"
27+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import kotlinx.coroutines.*
2+
import kotlin.system.measureTimeMillis
3+
4+
5+
fun main() = runBlocking { // Creates a blocking coroutine that executes in current thread (main)
6+
7+
println("Main program starts: ${Thread.currentThread().name}") // main thread
8+
9+
val time = measureTimeMillis {
10+
val msgOne: Deferred<String> = async {
11+
// ..more code..
12+
getMessageOne()
13+
}
14+
val msgTwo: Deferred<String> = async {
15+
// ..more code..
16+
getMessageTwo()
17+
}
18+
println("The entire message is: ${msgOne.await() + msgTwo.await()}")
19+
}
20+
21+
println("Completed in $time ms")
22+
println("Main program ends: ${Thread.currentThread().name}") // main thread
23+
}
24+
25+
suspend fun getMessageOne(): String {
26+
delay(1000L) // pretend to do some work
27+
return "Hello "
28+
}
29+
30+
suspend fun getMessageTwo(): String {
31+
delay(1000L) // pretend to do some work
32+
return "World!"
33+
}

src/76_lazy_async.kt

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
2+
import kotlinx.coroutines.*
3+
4+
fun main() = runBlocking { // Creates a blocking coroutine that executes in current thread (main)
5+
6+
println("Main program starts: ${Thread.currentThread().name}") // main thread
7+
8+
val msgOne: Deferred<String> = async(start = CoroutineStart.LAZY) { getMessageOne() }
9+
val msgTwo: Deferred<String> = async(start = CoroutineStart.LAZY) { getMessageTwo() }
10+
println("The entire message is: ${msgOne.await() + msgTwo.await()}")
11+
12+
println("Main program ends: ${Thread.currentThread().name}") // main thread
13+
}
14+
15+
suspend fun getMessageOne(): String {
16+
delay(1000L) // pretend to do some work
17+
println("After working in getMessageOne()")
18+
return "Hello "
19+
}
20+
21+
suspend fun getMessageTwo(): String {
22+
delay(1000L) // pretend to do some work
23+
println("After working in getMessageTwo()")
24+
return "World!"
25+
}

0 commit comments

Comments
 (0)