未激发协同路由流的Android回调
我有一个服务,其中数据由可变LiveData支持,并通过流对外公开未激发协同路由流的Android回调,android,kotlin,android-livedata,kotlin-coroutines,coroutine,Android,Kotlin,Android Livedata,Kotlin Coroutines,Coroutine,我有一个服务,其中数据由可变LiveData支持,并通过流对外公开 @ApplicationScope @Singleton class UserProfileServiceImpl : UserProfileService { private var userLiveData: MutableLiveData<UserProfile?> = MutableLiveData() override fun currentUser() = userLiveData.v
@ApplicationScope
@Singleton
class UserProfileServiceImpl : UserProfileService {
private var userLiveData: MutableLiveData<UserProfile?> = MutableLiveData()
override fun currentUser() = userLiveData.value
override fun updatePoints(points: Int) {
val user = currentUser()
?: throw IllegalAccessException("user is not authenticated")
user.points = points
userLiveData.postValue(user)
}
override suspend fun currentUserFlow(): Flow<UserProfile?> =
callbackFlow {
userLiveData.observeForever {
offer(it)
}
}
}
首先,如果您使用的是
androidx.lifecycle:lifecycle livedata ktx
工件,那么只需使用livedata.asFlow()
如果确实要使用callbackFlow
滚动自定义实现,则需要在流生成器中调用waitclose{…}
,否则它将被视为立即完成
override suspend fun currentUserFlow(): Flow<UserProfile?> =
callbackFlow {
val observer = Observer<UserProfile?>{
offer(it)
}
userLiveData.observeForever(observer)
awaitClose{
// called when the flow is no longer collected, e.g. the collecting
// CoroutineScope has been cancelled
userLiveData.removeObserver(observer)
}
}
覆盖当前用户流():流=
回叫{
观察者{
提供(it)
}
userLiveData.ObserveForver(观察者)
等待结束{
//不再收集流时调用,例如收集
//合作计划已被取消
userLiveData.removeObserver(观察者)
}
}
首先,如果您使用的是androidx.lifecycle:lifecycle livedata ktx
工件,您只需使用livedata.asFlow()
如果确实要使用callbackFlow
滚动自定义实现,则需要在流生成器中调用waitclose{…}
,否则它将被视为立即完成
override suspend fun currentUserFlow(): Flow<UserProfile?> =
callbackFlow {
val observer = Observer<UserProfile?>{
offer(it)
}
userLiveData.observeForever(observer)
awaitClose{
// called when the flow is no longer collected, e.g. the collecting
// CoroutineScope has been cancelled
userLiveData.removeObserver(observer)
}
}
覆盖当前用户流():流=
回叫{
观察者{
提供(it)
}
userLiveData.ObserveForver(观察者)
等待结束{
//不再收集流时调用,例如收集
//合作计划已被取消
userLiveData.removeObserver(观察者)
}
}
仅供参考,如果视图当前不可见,MutableLiveData不会更新该值。确保这不是你的问题。如果我发现与我上述观点相关的参考资料,我会附上一些参考资料。关于你的第一个问题:是的。LiveData上的Flow的主要优点是它限制了对Android特定API的依赖,但是如果你让它依赖LiveData,那就浪费了。可以使用StateFlow代替LiveData。仅供参考,如果视图当前不可见,则MutableLiveData不会更新该值。确保这不是你的问题。如果我发现与我上述观点相关的参考资料,我会附上一些参考资料。关于你的第一个问题:是的。LiveData上的Flow的主要优点是它限制了对Android特定API的依赖,但是如果你让它依赖LiveData,那就浪费了。StateFlow可以代替LiveData使用。谢谢。这回答了我所有的问题。听起来我好像忘记了流,把一切都建立在实时数据上,当我需要使用它时,我只是把它作为流提供。谢谢,这回答了我所有的问题。听起来我好像忘记了流,而是在实时数据上构建一切,当我需要使用它时,我只是将它作为流提供