【问题标题】:Kotlin channel not ready to send events after put app in background将应用程序置于后台后,Kotlin 通道未准备好发送事件
【发布时间】:2020-03-10 16:49:31
【问题描述】:

将应用置于后台后,Kotlin 通道停止发送事件(不要保持活动启用)

class UserRepositoryImpl(
    private val userRequestDataSource: UserRequestDataSourceContract,
) : UserRepositoryContract {

private var loginToken: LoginTokenDecode? = null
private val authChannel by lazy { Channel<Boolean?>() }

override suspend fun requestLogin(userLoginBo: UserLoginRequestBo){
   // isClosedForSend is true after putting app in background
   if(!authChannel.isClosedForSend)  {
     authChannel.send(true)
   }
}

视图模型

class UserViewModel : ViewModel {
  init {
     authChannelUc.invoke(scope = viewModelScope, onResult = ::authenticated)
  }
 ...
}

【问题讨论】:

  • 用户存储库合同的范围或生命周期是多少?
  • @GiorgosNeokleous 视图模型范围

标签: android kotlin channel kotlin-coroutines


【解决方案1】:

在消费者方面,使用for

 for (token in authChannel) {
      withContext(dispatcherForLaunch) {
         onResult(isTokenValid(loginTokenDecode))
      }
 } 

改为authChannel.consumerEach())

【讨论】:

    【解决方案2】:

    根据您使用viewModelScope 的评论;以及您在设备上启用了“不要将活动保持在后台”这一事实 - 活动在后台被杀死,这会取消 viewModelScope,它会自动关闭频道。

    【讨论】:

    • 但是当我来到应用程序时,视图模型被重新创建并再次发送视图模型范围
    • 视图模型仅保留用于设备旋转,而不是在像您这样的情况下用于重新启动活动。对于您的用例,我认为您需要一个后台服务,该服务不在 viewModelScope 中。
    猜你喜欢
    • 1970-01-01
    • 2022-11-14
    • 2020-08-17
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    • 2020-11-24
    相关资源
    最近更新 更多