Concetti e implementazione di Jetpack Compose
Offri un'esperienza utente migliore assicurandoti che la tua app possa essere utilizzata quando le connessioni di rete non sono affidabili o quando l'utente è offline. Un modo per farlo è eseguire l'impaginazione contemporaneamente dalla rete e da un database locale. In questo modo, l'app gestisce la UI da una cache del database locale ed effettua richieste alla rete solo quando non sono presenti altri dati nel database.
Questa guida presuppone che tu abbia familiarità con la libreria di persistenza Room e con l'utilizzo di base della libreria Paging.
Coordinare i caricamenti dei dati
La libreria Paging fornisce il componente RemoteMediator per questo caso d'uso. RemoteMediator funge da indicatore della libreria Paging quando l'app ha esaurito i dati memorizzati nella cache. Puoi utilizzare questo indicatore per caricare dati aggiuntivi dalla rete e archiviarli nel database locale, dove un PagingSource può caricarli e fornirli alla UI per la visualizzazione.
Quando sono necessari dati aggiuntivi, la libreria Paging chiama il metodo load() dall'implementazione di RemoteMediator. Si tratta di una funzione di sospensione, quindi è sicuro eseguire operazioni a lunga esecuzione. In genere, questa funzione recupera i nuovi dati da un'origine di rete e li salva nello spazio di archiviazione locale.
Questo processo funziona con i nuovi dati, ma nel tempo i dati archiviati nel database richiedono l'annullamento della convalida, ad esempio quando l'utente attiva manualmente un aggiornamento. Questo è rappresentato dalla proprietà LoadType passata al metodo load(). LoadType informa
RemoteMediator se deve aggiornare i dati esistenti o recuperare
dati aggiuntivi da aggiungere all'inizio o alla fine dell'elenco esistente.
In questo modo, RemoteMediator garantisce che l'app carichi i dati che gli utenti vogliono visualizzare nell'ordine appropriato.
Ciclo di vita della paginazione
Quando l'impaginazione viene eseguita direttamente dalla rete, PagingSource carica i dati e restituisce un oggetto LoadResult. L'implementazione PagingSource viene passata a
Pager tramite il
parametro pagingSourceFactory.
Quando la UI richiede nuovi dati, Pager chiama il metodo load() da PagingSource e restituisce uno stream di oggetti PagingData che incapsulano i nuovi dati. In genere, ogni oggetto PagingData viene memorizzato nella cache in ViewModel prima di essere inviato alla UI per la visualizzazione.
RemoteMediator modifica questo flusso di dati. Un PagingSource carica comunque i dati, ma quando i dati impaginati sono esauriti, la libreria Paging attiva RemoteMediator per caricare nuovi dati dall'origine di rete. RemoteMediator archivia i nuovi dati nel database locale, quindi non è necessaria una memoria cache in ViewModel. Infine, PagingSource si invalida e Pager crea una nuova istanza per caricare i dati aggiornati dal database.
Utilizzo di base
Supponiamo che tu voglia che la tua app carichi pagine di User elementi da un'origine dati di rete con chiave elemento in una cache locale archiviata in un database Room.
Un'implementazione di RemoteMediator aiuta a caricare i dati impaginati dalla rete nel database, ma non li carica direttamente nella UI. L'app utilizza invece il database come fonte di riferimento. In altre parole, l'app mostra solo i dati memorizzati nella cache del database. Un'implementazione di PagingSource (ad esempio, una generata da Room) gestisce il caricamento dei dati memorizzati nella cache dal database alla UI.
Crea entità Room
Il primo passaggio consiste nell'utilizzare la libreria di persistenza Room per definire un database che contiene una cache locale dei dati impaginati dall'origine dati di rete. Inizia con un'implementazione di RoomDatabase come descritto in Salva i dati in un database locale utilizzando Room.
Successivamente, definisci un'entità Room per rappresentare una tabella di elementi dell'elenco, come descritto in Definizione dei dati utilizzando le entità Room.
Assegnagli un campo id come chiave primaria, nonché campi per qualsiasi altra informazione contenuta negli elementi dell'elenco.
Java
@Entity(tableName = "users") public class User { public String id; public String label; }
Java
@Entity(tableName = "users") public class User { public String id; public String label; }
Devi anche definire un Data Access Object (DAO) per questa entità Room, come descritto in Accesso ai dati utilizzando i DAO di Room. Il DAO per l'entità dell'elemento dell'elenco deve includere i seguenti metodi:
- Un metodo
insertAll()che inserisce un elenco di elementi nella tabella. - Un metodo che accetta la stringa di query come parametro e restituisce un oggetto
PagingSourceper l'elenco dei risultati. In questo modo, un oggettoPagerpuò utilizzare questa tabella come origine dei dati impaginati. - Un metodo
clearAll()che elimina tutti i dati della tabella.
Java
@Dao interface UserDao { @Insert(onConflict = OnConflictStrategy.REPLACE) void insertAll(List<User> users); @Query("SELECT * FROM users WHERE mLabel LIKE :query") PagingSource<Integer, User> pagingSource(String query); @Query("DELETE FROM users") int clearAll(); }
Java
@Dao interface UserDao { @Insert(onConflict = OnConflictStrategy.REPLACE) void insertAll(List<User> users); @Query("SELECT * FROM users WHERE mLabel LIKE :query") PagingSource<Integer, User> pagingSource(String query); @Query("DELETE FROM users") int clearAll(); }
Implementa un RemoteMediator
Il ruolo principale di RemoteMediator è caricare più dati dalla rete quando
Pager esaurisce i dati o i dati esistenti non sono validi. Include un metodo load() che devi sostituire per definire il comportamento di caricamento.
Una tipica implementazione di RemoteMediator include i seguenti parametri:
query: una stringa di query che definisce i dati da recuperare dal servizio di backend.database: il database Room che funge da cache locale.networkService: un'istanza API per il servizio di backend.
Crea un'implementazione di RemoteMediator<Key, Value>. Il tipo Key e il tipo Value devono essere uguali a quelli che sarebbero se definissi un PagingSource per la stessa origine dati di rete. Per saperne di più sulla selezione dei parametri di tipo, consulta Seleziona i tipi di chiave e valore.
Java
@UseExperimental(markerClass = ExperimentalPagingApi.class) class ExampleRemoteMediator extends RxRemoteMediator<Integer, User> { private String query; private ExampleBackendService networkService; private RoomDb database; private UserDao userDao; ExampleRemoteMediator( String query, ExampleBackendService networkService, RoomDb database ) { query = query; networkService = networkService; database = database; userDao = database.userDao(); } @NotNull @Override public Single<MediatorResult> loadSingle( @NotNull LoadType loadType, @NotNull PagingState<Integer, User> state ) { ... } }
Java
class ExampleRemoteMediator extends ListenableFutureRemoteMediator<Integer, User> { private String query; private ExampleBackendService networkService; private RoomDb database; private UserDao userDao; private Executor bgExecutor; ExampleRemoteMediator( String query, ExampleBackendService networkService, RoomDb database, Executor bgExecutor ) { this.query = query; this.networkService = networkService; this.database = database; this.userDao = database.userDao(); this.bgExecutor = bgExecutor; } @NotNull @Override public ListenableFuture<MediatorResult> loadFuture( @NotNull LoadType loadType, @NotNull PagingState<Integer, User> state ) { ... } }
Il metodo load() è responsabile dell'aggiornamento del set di dati di supporto e dell'annullamento della convalida di PagingSource. Alcune librerie che supportano l'impaginazione (come Room)
gestiscono automaticamente l'annullamento della convalida degli oggetti PagingSource che
implementano.
Il metodo load() richiede due parametri:
PagingState, che contiene informazioni sulle pagine caricate finora, l'indice a cui è stato eseguito l'accesso più di recente e l'oggettoPagingConfigche hai utilizzato per inizializzare lo stream di paging.LoadType, che indica il tipo di carico:REFRESH,APPENDoPREPEND.
Il valore restituito del metodo load() è un oggetto MediatorResult. MediatorResult può essere
MediatorResult.Error
(che include la descrizione dell'errore) o
MediatorResult.Success
(che include un segnale che indica se sono presenti o meno altri dati da caricare).
Il metodo load() deve eseguire i seguenti passaggi:
- Determina quale pagina caricare dalla rete in base al tipo di caricamento e ai dati caricati finora.
- Attiva la richiesta di rete.
- Esegui le azioni in base al risultato dell'operazione di caricamento:
- Se il caricamento va a buon fine e l'elenco di elementi ricevuto non è vuoto,
memorizza gli elementi dell'elenco nel database e restituisci
MediatorResult.Success(endOfPaginationReached = false). Dopo aver archiviato i dati, invalida l'origine dati per notificare alla libreria Paging i nuovi dati. - Se il caricamento va a buon fine e l'elenco di elementi ricevuto è vuoto o è l'ultimo indice di pagina, restituisci
MediatorResult.Success(endOfPaginationReached = true). Una volta archiviati i dati, invalida l'origine dati per notificare alla libreria Paging i nuovi dati. - Se la richiesta genera un errore, restituisci
MediatorResult.Error.
- Se il caricamento va a buon fine e l'elenco di elementi ricevuto non è vuoto,
memorizza gli elementi dell'elenco nel database e restituisci
Java
@NotNull @Override public Single<MediatorResult> loadSingle( @NotNull LoadType loadType, @NotNull PagingState<Integer, User> state ) { // The network load method takes an optional after=<user.id> parameter. For // every page after the first, pass the last user ID to let it continue from // where it left off. For REFRESH, pass null to load the first page. String loadKey = null; switch (loadType) { case REFRESH: break; case PREPEND: // In this example, you never need to prepend, since REFRESH will always // load the first page in the list. Immediately return, reporting end of // pagination. return Single.just(new MediatorResult.Success(true)); case APPEND: User lastItem = state.lastItemOrNull(); // You must explicitly check if the last item is null when appending, // since passing null to networkService is only valid for initial load. // If lastItem is null it means no items were loaded after the initial // REFRESH and there are no more items to load. if (lastItem == null) { return Single.just(new MediatorResult.Success(true)); } loadKey = lastItem.getId(); break; } return networkService.searchUsers(query, loadKey) .subscribeOn(Schedulers.io()) .map((Function<SearchUserResponse, MediatorResult>) response -> { database.runInTransaction(() -> { if (loadType == LoadType.REFRESH) { userDao.deleteByQuery(query); } // Insert new users into database, which invalidates the current // PagingData, allowing Paging to present the updates in the DB. userDao.insertAll(response.getUsers()); }); return new MediatorResult.Success(response.getNextKey() == null); }) .onErrorResumeNext(e -> { if (e instanceof IOException || e instanceof HttpException) { return Single.just(new MediatorResult.Error(e)); } return Single.error(e); }); }
Java
@NotNull @Override public ListenableFuture<MediatorResult> loadFuture( @NotNull LoadType loadType, @NotNull PagingState<Integer, User> state ) { // The network load method takes an optional after=<user.id> parameter. For // every page after the first, pass the last user ID to let it continue from // where it left off. For REFRESH, pass null to load the first page. String loadKey = null; switch (loadType) { case REFRESH: break; case PREPEND: // In this example, you never need to prepend, since REFRESH will always // load the first page in the list. Immediately return, reporting end of // pagination. return Futures.immediateFuture(new MediatorResult.Success(true)); case APPEND: User lastItem = state.lastItemOrNull(); // You must explicitly check if the last item is null when appending, // since passing null to networkService is only valid for initial load. // If lastItem is null it means no items were loaded after the initial // REFRESH and there are no more items to load. if (lastItem == null) { return Futures.immediateFuture(new MediatorResult.Success(true)); } loadKey = lastItem.getId(); break; } ListenableFuture<MediatorResult> networkResult = Futures.transform( networkService.searchUsers(query, loadKey), response -> { database.runInTransaction(() -> { if (loadType == LoadType.REFRESH) { userDao.deleteByQuery(query); } // Insert new users into database, which invalidates the current // PagingData, allowing Paging to present the updates in the DB. userDao.insertAll(response.getUsers()); }); return new MediatorResult.Success(response.getNextKey() == null); }, bgExecutor); ListenableFuture<MediatorResult> ioCatchingNetworkResult = Futures.catching( networkResult, IOException.class, MediatorResult.Error::new, bgExecutor ); return Futures.catching( ioCatchingNetworkResult, HttpException.class, MediatorResult.Error::new, bgExecutor ); }
Definisci il metodo initialize
Le implementazioni di RemoteMediator possono anche eseguire l'override del metodo initialize() per verificare se i dati memorizzati nella cache non sono aggiornati e decidere se attivare un aggiornamento remoto. Questo metodo viene eseguito prima di qualsiasi caricamento, quindi puoi manipolare il database (ad esempio per cancellare i dati precedenti) prima di attivare qualsiasi caricamento locale o remoto.
Poiché initialize() è una funzione asincrona, puoi caricare i dati per determinare la pertinenza dei dati esistenti nel database. Il caso più comune è che i dati memorizzati nella cache siano validi solo per un determinato periodo di tempo. RemoteMediator può verificare se questa scadenza è passata, nel qual caso la libreria Paging deve aggiornare completamente i dati. Le implementazioni di initialize() devono restituire un InitializeAction come segue:
- Nei casi in cui i dati locali devono essere aggiornati completamente,
initialize()dovrebbe restituireInitializeAction.LAUNCH_INITIAL_REFRESH. In questo modo,RemoteMediatoresegue un aggiornamento remoto per ricaricare completamente i dati. I caricamenti remoti diAPPENDoPREPENDattendono il completamento del caricamento diREFRESHprima di procedere. - Nei casi in cui non è necessario aggiornare i dati locali,
initialize()dovrebbe restituireInitializeAction.SKIP_INITIAL_REFRESH. In questo modo,RemoteMediatorsalta l'aggiornamento remoto e carica i dati memorizzati nella cache.
Java
@NotNull @Override public Single<InitializeAction> initializeSingle() { long cacheTimeout = TimeUnit.MILLISECONDS.convert(1, TimeUnit.HOURS); return mUserDao.lastUpdatedSingle() .map(lastUpdatedMillis -> { if (System.currentTimeMillis() - lastUpdatedMillis <= cacheTimeout) { // Cached data is up-to-date, so there is no need to re-fetch // from the network. return InitializeAction.SKIP_INITIAL_REFRESH; } else { // Need to refresh cached data from network; returning // LAUNCH_INITIAL_REFRESH here will also block RemoteMediator's // APPEND and PREPEND from running until REFRESH succeeds. return InitializeAction.LAUNCH_INITIAL_REFRESH; } }); }
Java
@NotNull @Override public ListenableFuture<InitializeAction> initializeFuture() { long cacheTimeout = TimeUnit.MILLISECONDS.convert(1, TimeUnit.HOURS); return Futures.transform( mUserDao.lastUpdated(), lastUpdatedMillis -> { if (System.currentTimeMillis() - lastUpdatedMillis <= cacheTimeout) { // Cached data is up-to-date, so there is no need to re-fetch // from the network. return InitializeAction.SKIP_INITIAL_REFRESH; } else { // Need to refresh cached data from network; returning // LAUNCH_INITIAL_REFRESH here will also block RemoteMediator's // APPEND and PREPEND from running until REFRESH succeeds. return InitializeAction.LAUNCH_INITIAL_REFRESH; } }, mBgExecutor); }
Crea un pager
Infine, devi creare un'istanza Pager per configurare lo stream di dati impaginati.
Questa operazione è simile alla creazione di un Pager da un'origine dati di rete semplice, ma ci sono due cose che devi fare in modo diverso:
- Anziché passare direttamente un costruttore
PagingSource, devi fornire il metodo di query che restituisce un oggettoPagingSourcedal DAO. - Devi fornire un'istanza della tua implementazione di
RemoteMediatorcome parametroremoteMediator.
Java
UserDao userDao = database.userDao(); Pager<Integer, User> pager = Pager( new PagingConfig(/* pageSize = */ 20), null, // initialKey, new ExampleRemoteMediator(query, database, networkService) () -> userDao.pagingSource(query));
Java
UserDao userDao = database.userDao(); Pager<Integer, User> pager = Pager( new PagingConfig(/* pageSize = */ 20), null, // initialKey new ExampleRemoteMediator(query, database, networkService, bgExecutor), () -> userDao.pagingSource(query));
Gestisci le chiavi remote
Le chiavi remote sono chiavi utilizzate da un'implementazione di RemoteMediator per indicare al servizio di backend quali dati caricare successivamente. Nel caso più semplice, ogni elemento dei dati impaginati include una chiave remota a cui puoi fare riferimento facilmente. Tuttavia, se le chiavi remote non corrispondono a singoli elementi, devi memorizzarle separatamente e gestirle nel metodo load().
Questa sezione descrive come raccogliere, archiviare e aggiornare le chiavi remote che non sono archiviate in singoli elementi.
Chiavi degli elementi
Questa sezione descrive come utilizzare le chiavi remote che corrispondono a singoli elementi. In genere, quando una chiave API si basa su singoli elementi, l'ID articolo viene passato come parametro di query. Il nome del parametro indica se il server deve rispondere con elementi prima o dopo l'ID fornito. Nell'esempio della classe del modello User, il campo id del server viene utilizzato come chiave remota quando vengono richiesti dati aggiuntivi.
Quando il metodo load() deve gestire chiavi remote specifiche per gli elementi, queste chiavi sono in genere gli ID dei dati recuperati dal server. Le operazioni di aggiornamento non richiedono una chiave di caricamento, perché recuperano semplicemente i dati più recenti.
Analogamente, le operazioni di aggiunta all'inizio non devono recuperare dati aggiuntivi perché l'aggiornamento estrae sempre i dati più recenti dal server.
Tuttavia, le operazioni di aggiunta richiedono un ID. Ciò richiede il caricamento dell'ultimo elemento dal database e l'utilizzo del relativo ID per caricare la pagina di dati successiva. Se non sono presenti elementi nel database, endOfPaginationReached viene impostato su true, a indicare che è necessario un aggiornamento dei dati.
Java
@NotNull @Override public Single>MediatorResult< loadSingle( @NotNull LoadType loadType, @NotNull PagingState>Integer, User< state ) { // The network load method takes an optional String parameter. For every page // after the first, pass the String token returned from the previous page to // let it continue from where it left off. For REFRESH, pass null to load the // first page. Single>String< remoteKeySingle = null; switch (loadType) { case REFRESH: // Initial load should use null as the page key, so you can return null // directly. remoteKeySingle = Single.just(null); break; case PREPEND: // In this example, you never need to prepend, since REFRESH will always // load the first page in the list. Immediately return, reporting end of // pagination. return Single.just(new MediatorResult.Success(true)); case APPEND: User lastItem = state.lastItemOrNull(); // You must explicitly check if the last item is null when // appending, since passing null to networkService is only // valid for initial load. If lastItem is null it means no // items were loaded after the initial REFRESH and there are // no more items to load. if (lastItem == null) { return Single.just(new MediatorResult.Success(true)); } remoteKeySingle = Single.just(lastItem.getId()); break; } return remoteKeySingle .subscribeOn(Schedulers.io()) .flatMap((Function<String, Single<MediatorResult>>) remoteKey -> { return networkService.searchUsers(query, remoteKey) .map(response -> { database.runInTransaction(() -> { if (loadType == LoadType.REFRESH) { userDao.deleteByQuery(query); } // Insert new users into database, which invalidates the current // PagingData, allowing Paging to present the updates in the DB. userDao.insertAll(response.getUsers()); }); return new MediatorResult.Success(response.getUsers().isEmpty()); }); }) .onErrorResumeNext(e -> { if (e instanceof IOException || e instanceof HttpException) { return Single.just(new MediatorResult.Error(e)); } return Single.error(e); }); }
Java
@NotNull @Override public ListenableFuture<MediatorResult> loadFuture( @NotNull LoadType loadType, @NotNull PagingState<Integer, User> state ) { // The network load method takes an optional after=<user.id> parameter. // For every page after the first, pass the last user ID to let it continue // from where it left off. For REFRESH, pass null to load the first page. ResolvableFuture<String> remoteKeyFuture = ResolvableFuture.create(); switch (loadType) { case REFRESH: remoteKeyFuture.set(null); break; case PREPEND: // In this example, you never need to prepend, since REFRESH will always // load the first page in the list. Immediately return, reporting end of // pagination. return Futures.immediateFuture(new MediatorResult.Success(true)); case APPEND: User lastItem = state.lastItemOrNull(); // You must explicitly check if the last item is null when appending, // since passing null to networkService is only valid for initial load. // If lastItem is null it means no items were loaded after the initial // REFRESH and there are no more items to load. if (lastItem == null) { return Futures.immediateFuture(new MediatorResult.Success(true)); } remoteKeyFuture.set(lastItem.getId()); break; } return Futures.transformAsync(remoteKeyFuture, remoteKey -> { ListenableFuture<MediatorResult> networkResult = Futures.transform( networkService.searchUsers(query, remoteKey), response -> { database.runInTransaction(() -> { if (loadType == LoadType.REFRESH) { userDao.deleteByQuery(query); } // Insert new users into database, which invalidates the current // PagingData, allowing Paging to present the updates in the DB. userDao.insertAll(response.getUsers()); }); return new MediatorResult.Success(response.getUsers().isEmpty()); }, bgExecutor); ListenableFuture<MediatorResult> ioCatchingNetworkResult = Futures.catching( networkResult, IOException.class, MediatorResult.Error::new, bgExecutor ); return Futures.catching( ioCatchingNetworkResult, HttpException.class, MediatorResult.Error::new, bgExecutor ); }, bgExecutor); }
Chiavi di pagina
Questa sezione descrive come utilizzare le chiavi remote che non corrispondono a singoli elementi.
Aggiungi tabella delle chiavi remote
Quando le chiavi remote non sono associate direttamente agli elementi dell'elenco, è meglio archiviarle in una tabella separata nel database locale. Definisci un'entità Room che rappresenta una tabella di chiavi remote:
Java
@Entity(tableName = "remote_keys") public class RemoteKey { public String label; public String nextKey; }
Java
@Entity(tableName = "remote_keys") public class RemoteKey { public String label; public String nextKey; }
Devi anche definire un DAO per l'entità RemoteKey:
Java
@Dao interface RemoteKeyDao { @Insert(onConflict = OnConflictStrategy.REPLACE) void insertOrReplace(RemoteKey remoteKey); @Query("SELECT * FROM remote_keys WHERE label = :query") Single<RemoteKey> remoteKeyByQuerySingle(String query); @Query("DELETE FROM remote_keys WHERE label = :query") void deleteByQuery(String query); }
Java
@Dao interface RemoteKeyDao { @Insert(onConflict = OnConflictStrategy.REPLACE) void insertOrReplace(RemoteKey remoteKey); @Query("SELECT * FROM remote_keys WHERE label = :query") ListenableFuture<RemoteKey> remoteKeyByQueryFuture(String query); @Query("DELETE FROM remote_keys WHERE label = :query") void deleteByQuery(String query); }
Carica con chiavi remote
Quando il metodo load() deve gestire le chiavi di pagina remote, devi definirlo in modo diverso rispetto all'utilizzo di base di RemoteMediator:
- Includi una proprietà aggiuntiva che contiene un riferimento al DAO per la tabella delle chiavi remote.
- Determina quale chiave caricare successivamente eseguendo una query sulla tabella delle chiavi remote anziché utilizzare
PagingState. - Inserisci o archivia la chiave remota restituita dall'origine dati di rete oltre ai dati impaginati stessi.
Java
@NotNull @Override public Single<MediatorResult> loadSingle( @NotNull LoadType loadType, @NotNull PagingState<Integer, User> state ) { // The network load method takes an optional String parameter. For every page // after the first, pass the String token returned from the previous page to // let it continue from where it left off. For REFRESH, pass null to load the // first page. Single<RemoteKey> remoteKeySingle = null; switch (loadType) { case REFRESH: // Initial load should use null as the page key, so you can return null // directly. remoteKeySingle = Single.just(new RemoteKey(mQuery, null)); break; case PREPEND: // In this example, you never need to prepend, since REFRESH will always // load the first page in the list. Immediately return, reporting end of // pagination. return Single.just(new MediatorResult.Success(true)); case APPEND: // Query remoteKeyDao for the next RemoteKey. remoteKeySingle = mRemoteKeyDao.remoteKeyByQuerySingle(mQuery); break; } return remoteKeySingle .subscribeOn(Schedulers.io()) .flatMap((Function<RemoteKey, Single<MediatorResult>>) remoteKey -> { // You must explicitly check if the page key is null when appending, // since null is only valid for initial load. If you receive null // for APPEND, that means you have reached the end of pagination and // there are no more items to load. if (loadType != REFRESH && remoteKey.getNextKey() == null) { return Single.just(new MediatorResult.Success(true)); } return networkService.searchUsers(query, remoteKey.getNextKey()) .map(response -> { database.runInTransaction(() -> { if (loadType == LoadType.REFRESH) { userDao.deleteByQuery(query); remoteKeyDao.deleteByQuery(query); } // Update RemoteKey for this query. remoteKeyDao.insertOrReplace(new RemoteKey(query, response.getNextKey())); // Insert new users into database, which invalidates the current // PagingData, allowing Paging to present the updates in the DB. userDao.insertAll(response.getUsers()); }); return new MediatorResult.Success(response.getNextKey() == null); }); }) .onErrorResumeNext(e -> { if (e instanceof IOException || e instanceof HttpException) { return Single.just(new MediatorResult.Error(e)); } return Single.error(e); }); }
Java
@NotNull @Override public ListenableFuture<MediatorResult> loadFuture( @NotNull LoadType loadType, @NotNull PagingState<Integer, User> state ) { // The network load method takes an optional after=<user.id> parameter. For // every page after the first, pass the last user ID to let it continue from // where it left off. For REFRESH, pass null to load the first page. ResolvableFuture<RemoteKey> remoteKeyFuture = ResolvableFuture.create(); switch (loadType) { case REFRESH: remoteKeyFuture.set(new RemoteKey(query, null)); break; case PREPEND: // In this example, you never need to prepend, since REFRESH will always // load the first page in the list. Immediately return, reporting end of // pagination. return Futures.immediateFuture(new MediatorResult.Success(true)); case APPEND: User lastItem = state.lastItemOrNull(); // You must explicitly check if the last item is null when appending, // since passing null to networkService is only valid for initial load. // If lastItem is null it means no items were loaded after the initial // REFRESH and there are no more items to load. if (lastItem == null) { return Futures.immediateFuture(new MediatorResult.Success(true)); } // Query remoteKeyDao for the next RemoteKey. remoteKeyFuture.setFuture( remoteKeyDao.remoteKeyByQueryFuture(query)); break; } return Futures.transformAsync(remoteKeyFuture, remoteKey -> { // You must explicitly check if the page key is null when appending, // since null is only valid for initial load. If you receive null // for APPEND, that means you have reached the end of pagination and // there are no more items to load. if (loadType != LoadType.REFRESH && remoteKey.getNextKey() == null) { return Futures.immediateFuture(new MediatorResult.Success(true)); } ListenableFuture<MediatorResult> networkResult = Futures.transform( networkService.searchUsers(query, remoteKey.getNextKey()), response -> { database.runInTransaction(() -> { if (loadType == LoadType.REFRESH) { userDao.deleteByQuery(query); remoteKeyDao.deleteByQuery(query); } // Update RemoteKey for this query. remoteKeyDao.insertOrReplace(new RemoteKey(query, response.getNextKey())); // Insert new users into database, which invalidates the current // PagingData, allowing Paging to present the updates in the DB. userDao.insertAll(response.getUsers()); }); return new MediatorResult.Success(response.getNextKey() == null); }, bgExecutor); ListenableFuture<MediatorResult> ioCatchingNetworkResult = Futures.catching( networkResult, IOException.class, MediatorResult.Error::new, bgExecutor ); return Futures.catching( ioCatchingNetworkResult, HttpException.class, MediatorResult.Error::new, bgExecutor ); }, bgExecutor); }
Risorse aggiuntive
Per scoprire di più sulla libreria Paging, consulta le seguenti risorse aggiuntive:
Esempi
Consigliati per te
- Nota: il testo del link viene visualizzato quando JavaScript è disattivato
- Carica e visualizza i dati impaginati
- Testa l'implementazione di Paging
- Esegui la migrazione a Paging 3