如何从流量后的另一个函数中发出发射。STATEIN()()?

发布于 2025-02-03 07:26:23 字数 518 浏览 4 评论 0原文

我从数据库中获取页面数据,我有一个返回流程的存储库。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

樱娆 2025-02-10 07:26:24

如果您仅发出一个值,我看不出使用存储库中的流量的原因。我会将其更改为暂停函数,在viewModel中,我将用新值更新类型mutableStateFlow的变量。示例代码看起来如下:

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) 
        }
    }    
}

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. 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) 
        }
    }    
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文