如何在Android中在不同的类之间共享数值?

huangapple go评论82阅读模式
英文:

How to share values between different classes in Android?

问题

目前,我正在开发一个应用程序,在这个应用程序中,我需要保存不同类型的数据值,并在需要时从多个类中访问这些数据。目前,我正在使用对象(单例)类来实现这一点,就像下面这样:

  1. object VLineDataHolder {
  2. private val _logsProgress = MutableStateFlow(0)
  3. val logsProgress: StateFlow<Int>
  4. get() = _logsProgress
  5. fun setLogsProgress(logsProgress: Int) {
  6. _logsProgress.value = logsProgress
  7. }
  8. }

我不确定我是否正在以正确的方式处理这个问题,实际上我不需要在用户退出应用程序后保留数据,这就是为什么我没有在这里使用 DataStore 或 SharedPreferences。是否有人可以解释这是否是一个好的解决方案?

英文:

Currently I am developing an app where I have to save values of different types of data and access the data from multiple classes when needed. Currently I am using Object(singleton) classes for that. like below:

  1. object VLineDataHolder {
  2. private val _logsProgress = MutableStateFlow(0)
  3. val logsProgress: StateFlow&lt;Int&gt;
  4. get() = _logsProgress
  5. fun setLogsProgress(logsProgress: Int) {
  6. _logsProgress.value = logsProgress
  7. }
  8. }

I am just not sure If I am doing it in a right way, I don't actually need to persist the data after user exits the app that's why I am not using any DataStore or SharedPreferences here. Can any one explain if it is the good solution or not?

答案1

得分: 1

你可以在单例类内部使用可变的共享流(MutableSharedFlow),创建一种类似总线(Bus)的模式。只需将数据推送到流中,然后从任何位置观察它。例如,当用户登录事件发生时,我想被通知。

  1. object EventBusKotlin {
  2. private val _events = MutableSharedFlow<AuthEvents>()
  3. val events = _events.asSharedFlow()
  4. suspend fun publish(event: AuthEvents) {
  5. _events.emit(event)
  6. }
  7. @OptIn(DelicateCoroutinesApi::class)
  8. suspend inline fun <reified T> subscribe(crossinline onEvent: (T) -> Unit) {
  9. events.filterIsInstance<T>()
  10. .collectLatest { event ->
  11. coroutineContext.ensureActive()
  12. onEvent(event)
  13. }
  14. }
  15. }
  16. sealed class AuthEvents
  17. data class LoginEvent(
  18. val userId: String,
  19. val userName: String
  20. ): AuthEvents()
  21. // 观察/订阅事件
  22. @Inject
  23. lateinit var eventBus: EventBusKotlin
  24. // 推送/发布事件
  25. suspend fun postLoginEvent(loginEvent: LoginEvent) {
  26. eventBus.publish(loginEvent)
  27. }
  28. // 订阅和监听最新事件
  29. fun subscribeLoginEvent(lifecycleOwner: LifecycleOwner) {
  30. lifecycleOwner.lifecycleScope.launch {
  31. eventBus.subscribe<AuthEvents> { event ->
  32. when (event) {
  33. is LoginEvent -> Log.d(
  34. "LoginEventHandler",
  35. "${event.userName} 登录成功"
  36. )
  37. }
  38. }
  39. }
  40. }
英文:

You can use mutuable shared flow inside singleton class and creating a Bus type pattern. Just push the data and observe it from anywhere. As example I want to be noticed whenever use login event happens

  1. object EventBusKotlin {
  2. private val _events = MutableSharedFlow&lt;AuthEvents&gt;()
  3. val events = _events.asSharedFlow()
  4. suspend fun publish(event: AuthEvents) {
  5. _events.emit(event)
  6. }
  7. @OptIn(DelicateCoroutinesApi::class)
  8. suspend inline fun &lt;reified T&gt; subscribe(crossinline onEvent: (T) -&gt; Unit) {
  9. events.filterIsInstance&lt;T&gt;()
  10. .collectLatest { event -&gt;
  11. coroutineContext.ensureActive()
  12. onEvent(event)
  13. }
  14. }
  15. }
  16. sealed class AuthEvents

Event model

  1. data class LoginEvent(
  2. val userId: String,
  3. val userName: String
  4. ):AuthEvents()

Observing/Subscribing

  1. @Inject
  2. lateinit var eventBus: EventBusKotlin
  3. //push/publish event
  4. suspend fun postLoginEvent(loginEvent: LoginEvent) {
  5. eventBus.publish(loginEvent)
  6. }
  7. // subscribing and listening latest event
  8. fun subscribeLoginEvent(lifecycleOwner: LifecycleOwner) {
  9. lifecycleOwner.lifecycleScope.launch {
  10. eventBus.subscribe&lt;AuthEvents&gt; { event -&gt;
  11. when (event) {
  12. is LoginEvent -&gt; Log.d(
  13. &quot;LoginEventHandler&quot;,
  14. &quot;${event.userName} logged-in successfully&quot;
  15. )
  16. }
  17. }
  18. }
  19. }

huangapple
  • 本文由 发表于 2023年3月1日 15:32:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75600693.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定