【发布时间】:2021-05-24 07:36:27
【问题描述】:
我有一项服务,其中数据由 MutableLiveData 支持并通过流向外部公开。
@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)
}
}
}
然后我监听片段视图模型的变化并且回调没有被调用
class ViewModel: ViewModel() {
fun startListeningToService() {
viewModelScope.launch {
profileService.currentUserFlow().collect {
// This is not getting fired
// Send data to another liveData that the activity is listening to
}
}
}
}
- 我让这件事变得复杂了吗?感觉像是经过了很多层 从 1 点到另一个点的数据?使用 a 真的有优势吗 流到这里?感觉就像只是使用 LiveData 会很多 更简单,不需要在两者之间进行翻译
- 即使这不是最好的设计,为什么回调没有被触发?
【问题讨论】:
-
仅供参考,如果视图当前不可见,MutableLiveData 不会更新值。确保这对您来说不是问题。如果我找到与上述观点相关的参考资料,我会附上一些参考资料。
-
关于你的第一个问题:是的。 Flow 优于 LiveData 的主要优势在于它限制了对特定于 Android 的 API 的依赖,但如果你让它依赖于 LiveData,那就浪费了。可以使用 StateFlow 代替 LiveData。
标签: android kotlin android-livedata kotlin-coroutines coroutine