From 3a3356a4bbf80d33ad2cb46ad95dac8be5b09b70 Mon Sep 17 00:00:00 2001 From: HuanCheng65 <22636177+HuanCheng65@users.noreply.github.com> Date: Sat, 11 Mar 2023 01:16:12 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=85=A8=E5=B1=80=E4=BA=8B=E4=BB=B6?= =?UTF-8?q?=E6=B5=81=20&=20=E5=88=87=E6=8D=A2=E8=B4=A6=E5=8F=B7=E4=BA=8B?= =?UTF-8?q?=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tieba/post/arch/GlobalEvent.kt | 35 +++++++++++++++++++ .../tieba/post/utils/AccountUtil.kt | 3 ++ 2 files changed, 38 insertions(+) create mode 100644 app/src/main/java/com/huanchengfly/tieba/post/arch/GlobalEvent.kt 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() }