将应用程序置于后台后,Kotlin 通道未准备好发送事件
Kotlin channel not ready to send events after put app in background
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)
}
...
}
根据您的评论,您正在使用 viewModelScope
;以及您在设备上启用了 "Do not keep activities in background" 的事实 - Activity 被杀到后台,这取消了 viewModelScope
,它会自动关闭频道。
在消费者端,使用for:
for (token in authChannel) {
withContext(dispatcherForLaunch) {
onResult(isTokenValid(loginTokenDecode))
}
}
改为authChannel.consumerEach())
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)
}
...
}
根据您的评论,您正在使用 viewModelScope
;以及您在设备上启用了 "Do not keep activities in background" 的事实 - Activity 被杀到后台,这取消了 viewModelScope
,它会自动关闭频道。
在消费者端,使用for:
for (token in authChannel) {
withContext(dispatcherForLaunch) {
onResult(isTokenValid(loginTokenDecode))
}
}
改为authChannel.consumerEach())