Last active
August 14, 2023 19:46
-
-
Save wickedev/e0e7e873acf7dfdadb7769f8eeff45a5 to your computer and use it in GitHub Desktop.
CoroutineTests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.coroutine | |
import io.kotest.core.spec.style.DescribeSpec | |
import io.kotest.matchers.shouldBe | |
import kotlinx.coroutines.* | |
import kotlinx.coroutines.reactive.awaitFirstOrNull | |
import kotlinx.coroutines.reactor.mono | |
import org.jooq.DSLContext | |
import org.jooq.impl.DSL | |
import kotlin.coroutines.CoroutineContext | |
import kotlin.coroutines.coroutineContext | |
data class DslContextCoroutineContext(val dslContext: DSLContext) | |
: AbstractCoroutineContextElement(DslContextCoroutineContext) { | |
companion object Key : CoroutineContext.Key<DslContextCoroutineContext> | |
} | |
/* class DslContextCoroutineContext(val dslContext: DSLContext) : CoroutineDispatcher() { // 혹시? | |
override fun isDispatchNeeded(context: CoroutineContext): Boolean = true // 이로 인해 dispatch 불렸지만 | |
override fun dispatch(context: CoroutineContext, block: Runnable) = Unit // block를 불러주지 않은 경우 hang | |
override fun toString(): String = "DslContextCoroutineContext($dslContext)" | |
} */ | |
suspend fun <T> DSLContext.transactional(block: suspend (DSLContext) -> T?): T? { | |
val current: CoroutineContext = coroutineContext.minusKey(Job) | |
return transactionPublisher { | |
it.dsl().let { tx -> | |
mono<T>(current + DslContextCoroutineContext(tx) + Dispatchers.Unconfined) { block(tx) } | |
} | |
}.awaitFirstOrNull() | |
} | |
class CoroutineTests : DescribeSpec({ | |
describe("coroutine builder") { | |
it("should be await value") { | |
val ctx = DSL.using("jdbc:h2:~/test;AUTO_SERVER=TRUE", "SA", "") | |
val result = ctx.transactional { | |
delay(1000) | |
"Hello" | |
} | |
result.shouldBe("Hello") | |
} | |
it("mono(coroutineContext) should be await value") { | |
val result = mono(coroutineContext.minusKey(Job)) { "Hello" }.awaitFirstOrNull() | |
result.shouldBe("Hello") | |
} | |
it("async(coroutineContext) should be await value") { | |
val result = async(coroutineContext) { "Hello" }.await() | |
result.shouldBe("Hello") | |
} | |
it("withContext(coroutineContext) should be await value") { | |
val result = withContext(coroutineContext) { "Hello" } | |
result.shouldBe("Hello") | |
} | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment