I’m looking for help using Paging3 where the `Flow...
# android-architecture
a
I’m looking for help using Paging3 where the
Flow<PagingData<T>>
is combined with another flow in the Repository, not the ViewModel. According to the Paging3 docs the
combine()
operator should be used with
.cachedIn(scope)
where scope is typically a ViewModel scope. I don’t think I should be passing this into the Repository like:
class FileRepository {
fun getPagedFiles(coroutineScope:CoroutineScope, query:Query):Flow<PagingData<DomainType> =
combine(
pager.flow.cachedIn(coroutineScope) // returns Room Entity
anotherFlow,
anotherFlow
) { a,b,c ->
...
}
I can 1. put the transformation in the ViewModel, using its scope, but then have to expose types in the Repository interface (pagingSource is from Room) that ideally should not be exposed (Room entities) 2. use some other scope, not the ViewModel scope
m
Personally, I think this is ok. For instance, if you want to directly subscribe to the flow in a composable you could pass the result of a "rememberCoroutineScope" call. it gives you a lot of flexibility. While i recommend that you use this from a view model, and thus use viewModelScope, you could very easy do it directly in a composable and use
rememberCoroutineScope()
to tie the lifecycle to your composable.
I've done exactly this recently in a POC i've been working on.
Copy code
override suspend fun monitor(scope: CoroutineScope): StateFlow<StringTable> =
        dataStore.data.map {
            PreferencesStringTable(it)
        }.stateIn(scope)
My general rule of thumb is to not assume what scope or dispatcher a particular service layer wants to use. Always pass it in (either as a constructor parameter or a function parameter), and provide a sensible default (like Dispatchers.IO if you have blocking io operation). That way you can easily test things too.