CoroutineUtils.kt 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright 2019-2021 Mamoe Technologies and contributors.
  3. *
  4. * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
  5. * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
  6. *
  7. * https://github.com/mamoe/mirai/blob/master/LICENSE
  8. */
  9. @file:JvmMultifileClass
  10. @file:JvmName("MiraiUtils")
  11. package net.mamoe.mirai.utils
  12. import kotlinx.coroutines.*
  13. import kotlinx.coroutines.sync.Semaphore
  14. import kotlinx.coroutines.sync.withPermit
  15. import kotlin.coroutines.CoroutineContext
  16. import kotlin.coroutines.EmptyCoroutineContext
  17. @Suppress("unused", "INVISIBLE_MEMBER", "INVISIBLE_REFERENCE", "DeprecatedCallableAddReplaceWith")
  18. @Deprecated(
  19. message = "Use runBIO which delegates to `runInterruptible`. " +
  20. "Technically remove suspend call in `block` and remove CoroutineScope parameter usages.",
  21. level = DeprecationLevel.WARNING
  22. )
  23. @kotlin.internal.LowPriorityInOverloadResolution
  24. public suspend inline fun <R> runBIO(
  25. noinline block: suspend CoroutineScope.() -> R
  26. ): R = withContext(Dispatchers.IO, block)
  27. public suspend inline fun <R> runBIO(
  28. noinline block: () -> R
  29. ): R = runInterruptible(context = Dispatchers.IO, block = block)
  30. public inline fun CoroutineScope.launchWithPermit(
  31. semaphore: Semaphore,
  32. coroutineContext: CoroutineContext = EmptyCoroutineContext,
  33. crossinline block: suspend () -> Unit
  34. ): Job {
  35. return launch(coroutineContext) {
  36. semaphore.withPermit { block() }
  37. }
  38. }
  39. /**
  40. * Creates a child scope of the receiver scope.
  41. */
  42. public fun CoroutineScope.childScope(
  43. coroutineContext: CoroutineContext = EmptyCoroutineContext,
  44. ): CoroutineScope {
  45. val ctx = this.coroutineContext + coroutineContext
  46. return CoroutineScope(ctx + SupervisorJob(ctx.job))
  47. }
  48. /**
  49. * Creates a child scope of the receiver context scope.
  50. */
  51. public fun CoroutineContext.childScope(
  52. coroutineContext: CoroutineContext = EmptyCoroutineContext,
  53. ): CoroutineScope {
  54. val ctx = this + coroutineContext
  55. return CoroutineScope(ctx + SupervisorJob(ctx.job))
  56. }