簡體   English   中英

"如何更新android協程中的流源數據?"

[英]How can I update the flow source data in android coroutine?

我正在使用 Coroutine 開發一個 android 應用程序。

因為我有 Rx 的經驗,所以我可以理解 Coroutine Flow 的概念。

但我不知道向現有流程發送新數據。

在 Rx 中,我可以使用BehaviorSubject<\/code>和它的onNext()<\/code>函數。

制片人:

class ProfileRepository(
    private val profileDao: ProfileDao
) {

    init {
        val profile = profileDao.getMyProfile()
        myProfile.onNext(profile)
    }

    val myProfile: PublishSubject<Profile> = BehaviorSubject.create()

    fun updateMyProfile(profile: Profile) {
        myProfile.onNext(profile)
    }

}

您正在使用BehaviorSubject<\/code> ,它在訂閱時發出最近的項目,然后繼續序列直到完成。 所以基本上它是一個熱數據流。

類似的行為有SharedFlow<\/code><\/a> :

一個 hotFlow,它以廣播方式在其所有收集器之間共享發出的值,以便所有收集器獲取所有發出的值。 共享流之所以稱為熱流,是因為它的活動實例獨立於收集器的存在而存在。

對於您的情況,它將如下所示:

 viewModelScope<\/code><\/a> - 如果ViewModel<\/code>被清除,在此范圍內啟動的任何協程都會自動取消。 對於ViewModelScope<\/code> ,使用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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