簡體   English   中英

未觸發協程流的 Android 回調

[英]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
            }
        }
    }
}
  1. 我讓這個復雜嗎? 感覺就像從一個點到另一個點的很多層傳遞數據? 在這里使用 Flow 真的有優勢嗎? 感覺只是使用 LiveData 會簡單得多,並且不需要在兩者之間進行轉換
  2. 即使這不是最好的設計,為什么回調沒有被觸發?

首先,如果您使用的是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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM