inheritCoroutineContext

expect inline suspend fun inheritCoroutineContext()

使用当前协程的 coroutineContext 作为 parentCoroutineContext.

Bot 将会使用一个 SupervisorJob 覆盖 coroutineContext 当前协程的 Job, 并使用当前协程的 Job 作为父 Job

用例:

coroutineScope {
val bot = Bot(...) {
inheritCoroutineContext()
}
bot.login()
} // coroutineScope 会等待 Bot 退出

注意: bot.cancel 时将会让父 Job 也被 cancel.

coroutineScope { // this: CoroutineScope
launch {
while(isActive) {
delay(500)
println("I'm alive")
}
}

val bot = Bot(...) {
inheritCoroutineContext() // 使用 `coroutineScope` 的 Job 作为父 Job
}
bot.login()
bot.cancel() // 取消了整个 `coroutineScope`, 因此上文不断打印 `"I'm alive"` 的协程也会被取消.
}

因此, 此函数尤为适合在 suspend fun main() 中使用, 它能阻止主线程退出:

suspend fun main() {
val bot = Bot() {
inheritCoroutineContext()
}
bot.eventChannel.subscribe { ... }

// 主线程不会退出, 直到 Bot 离线.
}

简言之,

See also

actual inline suspend fun inheritCoroutineContext()

使用当前协程的 coroutineContext 作为 parentCoroutineContext.

Bot 将会使用一个 SupervisorJob 覆盖 coroutineContext 当前协程的 Job, 并使用当前协程的 Job 作为父 Job

用例:

coroutineScope {
val bot = Bot(...) {
inheritCoroutineContext()
}
bot.login()
} // coroutineScope 会等待 Bot 退出

注意: bot.cancel 时将会让父 Job 也被 cancel.

coroutineScope { // this: CoroutineScope
launch {
while(isActive) {
delay(500)
println("I'm alive")
}
}

val bot = Bot(...) {
inheritCoroutineContext() // 使用 `coroutineScope` 的 Job 作为父 Job
}
bot.login()
bot.cancel() // 取消了整个 `coroutineScope`, 因此上文不断打印 `"I'm alive"` 的协程也会被取消.
}

因此, 此函数尤为适合在 suspend fun main() 中使用, 它能阻止主线程退出:

suspend fun main() {
val bot = Bot() {
inheritCoroutineContext()
}
bot.eventChannel.subscribe { ... }

// 主线程不会退出, 直到 Bot 离线.
}

简言之,

See also

actual inline suspend fun inheritCoroutineContext()

使用当前协程的 coroutineContext 作为 parentCoroutineContext.

Bot 将会使用一个 SupervisorJob 覆盖 coroutineContext 当前协程的 Job, 并使用当前协程的 Job 作为父 Job

用例:

coroutineScope {
val bot = Bot(...) {
inheritCoroutineContext()
}
bot.login()
} // coroutineScope 会等待 Bot 退出

注意: bot.cancel 时将会让父 Job 也被 cancel.

coroutineScope { // this: CoroutineScope
launch {
while(isActive) {
delay(500)
println("I'm alive")
}
}

val bot = Bot(...) {
inheritCoroutineContext() // 使用 `coroutineScope` 的 Job 作为父 Job
}
bot.login()
bot.cancel() // 取消了整个 `coroutineScope`, 因此上文不断打印 `"I'm alive"` 的协程也会被取消.
}

因此, 此函数尤为适合在 suspend fun main() 中使用, 它能阻止主线程退出:

suspend fun main() {
val bot = Bot() {
inheritCoroutineContext()
}
bot.eventChannel.subscribe { ... }

// 主线程不会退出, 直到 Bot 离线.
}

简言之,

See also