feat: 全局事件流 & 切换账号事件

This commit is contained in:
HuanCheng65 2023-03-11 01:16:12 +08:00
parent c104ae920e
commit 3a3356a4bb
No known key found for this signature in database
GPG Key ID: E9031EF91A805148
2 changed files with 38 additions and 0 deletions

View File

@ -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<GlobalEvent>() }
val GlobalEventFlow by lazy { mutableGlobalEventFlow }
fun emitGlobalEvent(event: GlobalEvent) {
mutableGlobalEventFlow.tryEmit(event)
}
inline fun <reified Event : GlobalEvent> CoroutineScope.onGlobalEvent(
noinline listener: suspend (Event) -> Unit
): Job {
return launch {
GlobalEventFlow
.filterIsInstance<Event>()
.cancellable()
.collect {
launch {
listener(it)
}
}
}
}

View File

@ -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()
}