[英]Android callback for a coroutine flow is not fired
我有一項服務,其中數據由 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
}
}
}
}
首先,如果您使用的是androidx.lifecycle:lifecycle-livedata-ktx
工件,您可以簡單地使用liveData.asFlow()
如果您確實想使用callbackFlow
滾動自定義實現,則需要在流程構建器中調用awaitClose{...}
,否則它將被視為立即完成。
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)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.