[英]How to initialize a flow in viewmodel with a suspend function as parameter
我正在使用房間數據庫和數據存儲。 這是我的代碼
視圖模型
@HiltViewModel
class SubscriptionViewModel @Inject constructor(
private val userDataStore: UserDataStore,
private val walletDao: WalletDao
) : ViewModel() {
val flow: Flow<List<Transaction>> = walletDao.getAllTransactions(userDataStore.getId())
// This shows an error as userDataStore.getId() is a suspend function in DataStore
init {
viewModelScope.launch(IO) {
getWalletAmount()
}
}
}
數據存儲
suspend fun getId(): String {
val preferences = dataStore.data.first()
return preferences[USER_ID] ?: ""
}
錢包道
@Query("SELECT * FROM recent_transactions where user_id=:user_id")
fun getAllTransactions(user_id: String): Flow<List<Transaction>>
問題是我無法初始化流程。 我嘗試使用 lateinit 在 init{ } 塊中對其進行初始化,但是在訪問片段時它崩潰了,說流尚未初始化。
任何解決方案都會有所幫助。
您可以將其包裝在流程構建器中。
val flow: Flow<List<Transaction>> = flow {
val source = walletDao.getAllTransactions(userDataStore.getId())
emitAll(source)
}
如果您希望它預先加載(甚至在任何東西收集流之前就開始獲取第一個值),那么您應該通過添加以下內容將其變成 SharedFlow:
.shareIn(viewModelScope, SharingStarted.Eagerly, replay = 1)
據我所知,您可以在變量中調用暫停樂趣,它必須在 init 或 function 中還有另一種解決方案
@HiltViewModel
class SubscriptionViewModel @Inject constructor(
private val userDataStore: UserDataStore,
private val walletDao: WalletDao
) : ViewModel() {
val flow= MutableStateFlow<List<Transcation>>(listOf())
// then add value in init or anywhere
init {
viewModelScope.launch(IO) {
flow.emit() // add value here
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.