diff --git a/mirai-core/src/commonTest/kotlin/network/framework/components/EventDispatcherImpl.kt b/mirai-core/src/commonTest/kotlin/network/framework/components/EventDispatcherImpl.kt index d38f171db..fb6b6a99d 100644 --- a/mirai-core/src/commonTest/kotlin/network/framework/components/EventDispatcherImpl.kt +++ b/mirai-core/src/commonTest/kotlin/network/framework/components/EventDispatcherImpl.kt @@ -1,15 +1,16 @@ /* - * Copyright 2019-2021 Mamoe Technologies and contributors. + * Copyright 2019-2022 Mamoe Technologies and contributors. * - * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证. - * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link. + * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证. + * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link. * - * https://github.com/mamoe/mirai/blob/master/LICENSE + * https://github.com/mamoe/mirai/blob/dev/LICENSE */ package network.framework.components import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.isActive import kotlinx.coroutines.job import kotlinx.coroutines.launch import net.mamoe.mirai.event.Event @@ -26,13 +27,21 @@ internal open class TestEventDispatcherImpl( ) : EventDispatcherImpl(lifecycleContext, logger) { override suspend fun broadcast(event: Event) { runUnwrapCancellationException { - launch( - EventDispatcherScopeFlag, - start = CoroutineStart.UNDISPATCHED - ) { + if (isActive) { + // This requires the scope to be active, while the original one doesn't. + + // so that [joinBroadcast] works. + launch( + EventDispatcherScopeFlag, + start = CoroutineStart.UNDISPATCHED + ) { + super.broadcast(event) + }.join() + } else { + // Scoped closed, typically when broadcasting `BotOfflineEvent` by StateObserver from `bot.close` super.broadcast(event) - }.join() - } // so that [joinBroadcast] works. + } + } } @OptIn(TestOnly::class)