Skip to content

Commit

Permalink
feat: flow example 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
huisam committed Nov 27, 2022
1 parent 000108a commit 0fa5c78
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/main/kotlin/com/huisam/kotlincoroutine/flow/Flow.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.huisam.kotlincoroutine.flow

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.runBlocking
import java.util.concurrent.atomic.AtomicLong

fun main(): Unit = runBlocking(Dispatchers.Default) {
val flowStartTime = AtomicLong(0L)

flow {
repeat(times = 3) { data ->
delay(300L)
produceLog(flowStartTime.get(), data)
emit(data)
}
}.onStart {
flowStartTime.set(System.currentTimeMillis())
}.collectLatest { data ->
delay(700L)
consumerLog(flowStartTime.get(), data)
}
}

private fun produceLog(flowStartTime: Long, data: Int) {
println(
"""
Time: ${elapsedFromStartTime(flowStartTime)}ms / Producer Coroutine : ${Thread.currentThread().name} / data : $data [>>]
""".trimIndent()
)
}

private fun consumerLog(flowStartTime: Long, data: Int) {
println(
"""
Time: ${elapsedFromStartTime(flowStartTime)}ms / Consumer Coroutine : ${Thread.currentThread().name} / data : $data [<<]
""".trimIndent()
)
}

private fun elapsedFromStartTime(flowStartTime: Long) = System.currentTimeMillis() - flowStartTime

0 comments on commit 0fa5c78

Please sign in to comment.