Improve Bot.isOnline: do not initialize network

This commit is contained in:
Him188 2021-09-12 20:41:30 +08:00
parent e3fd680a2c
commit 21513a92e4
2 changed files with 13 additions and 2 deletions

View File

@ -86,7 +86,7 @@ internal abstract class AbstractBot constructor(
*/
abstract val components: ComponentStorage
final override val isOnline: Boolean get() = network.state == State.OK
final override val isOnline: Boolean get() = if (!networkInitialized) false else network.state == State.OK
final override val eventChannel: EventChannel<BotEvent> =
GlobalEventChannel.filterIsInstance<BotEvent>().filter { it.bot === this@AbstractBot }
@ -119,7 +119,12 @@ internal abstract class AbstractBot constructor(
// network
///////////////////////////////////////////////////////////////////////////
val network: NetworkHandler by lazy { createNetworkHandler() } // the selector handles renewal of [NetworkHandler]
@Volatile
private var networkInitialized = false
val network: NetworkHandler by lazy {
networkInitialized = true
createNetworkHandler()
} // the selector handles renewal of [NetworkHandler]
final override suspend fun login() {
if (!isActive) error("Bot is already closed and cannot relogin. Please create a new Bot instance then do login.")

View File

@ -125,4 +125,10 @@ internal class NettyBotLifecycleTest : AbstractNettyNHTest() {
assertFalse { network.isActive }
network.assertState(CLOSED) // we do not use selector in this test so it will be CLOSED. It will recover (reconnect) instead in real.
}
@Test
fun `isOnline returns false if network not initialized`() = runBlockingUnit {
assertFalse { bot.isOnline }
}
}