diff --git a/app/src/main/java/com/huanchengfly/tieba/post/arch/GlobalEvent.kt b/app/src/main/java/com/huanchengfly/tieba/post/arch/GlobalEvent.kt new file mode 100644 index 00000000..894c8a1f --- /dev/null +++ b/app/src/main/java/com/huanchengfly/tieba/post/arch/GlobalEvent.kt @@ -0,0 +1,35 @@ +package com.huanchengfly.tieba.post.arch + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.cancellable +import kotlinx.coroutines.flow.filterIsInstance +import kotlinx.coroutines.launch + +sealed interface GlobalEvent { + object AccountSwitched : GlobalEvent +} + +private val mutableGlobalEventFlow by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { MutableSharedFlow() } + +val GlobalEventFlow by lazy { mutableGlobalEventFlow } + +fun emitGlobalEvent(event: GlobalEvent) { + mutableGlobalEventFlow.tryEmit(event) +} + +inline fun CoroutineScope.onGlobalEvent( + noinline listener: suspend (Event) -> Unit +): Job { + return launch { + GlobalEventFlow + .filterIsInstance() + .cancellable() + .collect { + launch { + listener(it) + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/huanchengfly/tieba/post/utils/AccountUtil.kt b/app/src/main/java/com/huanchengfly/tieba/post/utils/AccountUtil.kt index 61a2a370..15b3aa84 100644 --- a/app/src/main/java/com/huanchengfly/tieba/post/utils/AccountUtil.kt +++ b/app/src/main/java/com/huanchengfly/tieba/post/utils/AccountUtil.kt @@ -12,6 +12,8 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.staticCompositionLocalOf import com.huanchengfly.tieba.post.R import com.huanchengfly.tieba.post.api.TiebaApi +import com.huanchengfly.tieba.post.arch.GlobalEvent +import com.huanchengfly.tieba.post.arch.emitGlobalEvent import com.huanchengfly.tieba.post.models.database.Account import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.zip @@ -96,6 +98,7 @@ object AccountUtil { context.sendBroadcast(Intent().setAction(ACTION_SWITCH_ACCOUNT)) val account = runCatching { getAccountInfo(id) }.getOrNull() ?: return false mutableCurrentAccountState.value = account + emitGlobalEvent(GlobalEvent.AccountSwitched) return context.getSharedPreferences("accountData", Context.MODE_PRIVATE).edit() .putInt("now", id).commit() }