Android architecture: is RemoteMediator a DataSource itself for the repository class?

283 views Asked by At

I'm learning how to implement Paging (Jetpack Paging Library) and how to fetch data from both network and local database.

I have followed Google codelab and learned about the RemoteMediator class, which is very useful for me, because it handle network requests when data is needed, in an endless list.

Until now, I used a Repository with a NetworkDataSource and a LocalDataSource (and mappers), but with the mediator I'm confused about the correct usage, see code below.

class MainRepository(
    private val networkDataSource: NetworkDataSource,
    private val localDataSource: LocalDataSource,
    private val listMapper: ListMapper<Results, Entity>
) {
    
    fun getDatasStream(): Flow<PagingData<Entity>> {

        val pagingSourceFactory = {
            localDataSource.getDatas()
        }

        @OptIn(ExperimentalPagingApi::class)
        return Pager(
            config = PagingConfig(pageSize = NETWORK_PAGE_SIZE, enablePlaceholders = false),
            remoteMediator = DatasRemoteMediator(
                networkDataSource,
                localDataSource,
                listMapper
            ),
            pagingSourceFactory = pagingSourceFactory
        ).flow
    }

    companion object {
        const val NETWORK_PAGE_SIZE = 20
    }
}

As you can see, the repository create and pass the mediator to the Pager class, instantiated on function getDatasStream.

The code above is it correct? Or should I have to change the constructor of the repository in order to have only the DatasRemoteMediator as parameter and consider this class as the man in the middle?

0

There are 0 answers