如何从流量后的另一个函数中发出发射。STATEIN()()?
我从数据库中获取页面数据,我有一个返回流程的存储库。
class RepositoryImpl (private val db: AppDatabase) : Repository {
override fun fetchData (page: Int) = flow {
emit(db.getData(page))
}
}
在ViewModel中,我称为statein(),第一页到达,但是如何请求第二页?通过调用fetchdata(page = 2),我得到了一个新的流,我需要数据才能到达旧流程。
class ViewModel(private val repository: Repository) : ViewModel() {
val dataFlow = repository.fetchData(page = 1).stateIn(viewModelScope, WhileSubscribed())
}
如何获取数据流中的第二页?
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? By calling fetchData(page = 2) I get a new flow, and I need the data to arrive on the old flow.
class ViewModel(private val repository: Repository) : ViewModel() {
val dataFlow = repository.fetchData(page = 1).stateIn(viewModelScope, WhileSubscribed())
}
How to get the second page in dataFlow?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您仅发出一个值,我看不出使用存储库中的流量的原因。我会将其更改为
暂停
函数,在viewModel
中,我将用新值更新类型mutableStateFlow
的变量。示例代码看起来如下: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 theViewModel
I would update a variable of typeMutableStateFlow
with the new value. The sample code could look like the following: