[英]How to make an emit from another function in a flow after flow.stateIn()?
I get page data from a database, I have a repository that returns a flow.我从数据库中获取页面数据,我有一个返回流的存储库。
class RepositoryImpl (private val db: AppDatabase) : Repository {
override fun fetchData (page: Int) = flow {
emit(db.getData(page))
}
}
In the ViewModel, I call the stateIn(), the first page arrives, but then how to request the second page?在ViewModel中,我调用了stateIn(),第一页到了,那么如何请求第二页呢? By calling fetchData(page = 2) I get a new flow, and I need the data to arrive on the old flow.通过调用 fetchData(page = 2) 我得到一个新流,我需要数据到达旧流。
class ViewModel(private val repository: Repository) : ViewModel() {
val dataFlow = repository.fetchData(page = 1).stateIn(viewModelScope, WhileSubscribed())
}
How to get the second page in dataFlow?如何获取数据流中的第二页?
I don't see the reason to use a flow in the repository if you are emitting only one value.如果您只发出一个值,我看不出在存储库中使用流的原因。 I would change it to a suspend
function, and in the ViewModel
I would update a variable of type MutableStateFlow
with the new value.我会将其更改为suspend
函数,并在ViewModel
中使用新值更新MutableStateFlow
类型的变量。 The sample code could look like the following:示例代码可能如下所示:
class RepositoryImpl (private val db: AppDatabase) : Repository {
override suspend fun fetchData (page: Int): List<Data> {
return db.getData(page)
}
}
class ViewModel(private val repository: Repository) : ViewModel() {
val _dataFlow = MutableStateFlow<List<Data>>(emptyList())
val dataFlow = _dataFlow.asStateFlow()
fun fetchData (page: Int): List<Data> {
viewModelScope.launch {
_dataFlow.value = repository.fetchData(page)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.