דף מהרשת וממסד הנתונים (תצוגות)

מושגים והטמעה של Jetpack Compose

כדי לספק חוויית משתמש משופרת, חשוב לוודא שאפשר להשתמש באפליקציה גם כשהחיבור לרשת לא יציב או כשהמשתמש במצב אופליין. אחת מהדרכים לעשות את זה היא להציג דפים מהרשת וממסד נתונים מקומי בו-זמנית. כך האפליקציה מפעילה את ממשק המשתמש ממטמון של מסד נתונים מקומי, ושולחת בקשות לרשת רק כשאין יותר נתונים במסד הנתונים.

המדריך הזה מתבסס על ההנחה שאתם מכירים את ספריית Room persistence ואת השימוש הבסיסי בספריית Paging.

תיאום טעינת נתונים

ספריית Paging מספקת את הרכיב RemoteMediator לתרחיש לדוגמה הזה. RemoteMediator פועל כאות מספריית Paging כשהאפליקציה ניצלה את כל הנתונים שנשמרו במטמון. אתם יכולים להשתמש באות הזה כדי לטעון נתונים נוספים מהרשת ולאחסן אותם במסד הנתונים המקומי, שבו PagingSource יכול לטעון אותם ולספק אותם לממשק המשתמש כדי להציג אותם.

כשנדרשים נתונים נוספים, ספריית Paging מפעילה את ה-method‏ load() מההטמעה של RemoteMediator. זו פונקציית השהיה, אז אפשר לבצע בה עבודה שנמשכת זמן רב. הפונקציה הזו בדרך כלל מאחזרת את הנתונים החדשים ממקור ברשת ושומרת אותם באחסון המקומי.

התהליך הזה פועל עם נתונים חדשים, אבל עם הזמן צריך לבטל את התוקף של הנתונים שמאוחסנים במסד הנתונים, למשל כשהמשתמש מפעיל רענון באופן ידני. המאפיין הזה מיוצג על ידי המאפיין LoadType שמועבר ל-method‏ load(). ה-LoadType מודיע ל-RemoteMediator אם צריך לרענן את הנתונים הקיימים או לאחזר נתונים נוספים שצריך להוסיף לרשימה הקיימת.

כך RemoteMediator מבטיח שהאפליקציה תטען את הנתונים שהמשתמשים רוצים לראות בסדר הנכון.

מחזור החיים של Paging

תרשים 1. תרשים של מחזור החיים של Paging עם PagingSource ו-PagingData.

כשמבצעים חלוקה לדפים ישירות מהרשת, ה-PagingSource טוען את הנתונים ומחזיר אובייקט LoadResult. ההטמעה של PagingSource מועברת אל Pager באמצעות הפרמטר pagingSourceFactory.

כשהממשק צריך נתונים חדשים, ה-Pager קורא ל-method‏ load() מה-PagingSource ומחזיר זרם של אובייקטים מסוג PagingData שמכילים את הנתונים החדשים. בדרך כלל, כל אובייקט PagingData נשמר במטמון ב-ViewModel לפני שהוא נשלח לממשק המשתמש כדי להציג אותו.

איור 2. תרשים של מחזור החיים של Paging עם PagingSource ו-RemoteMediator.

‫RemoteMediator משנה את זרימת הנתונים הזו. PagingSource עדיין טוען את הנתונים, אבל כשהנתונים בדפים נגמרים, ספריית הדפדוף מפעילה את RemoteMediator כדי לטעון נתונים חדשים ממקור הרשת. ה-RemoteMediator מאחסן את הנתונים החדשים במסד הנתונים המקומי, כך שאין צורך במטמון בזיכרון ב-ViewModel. לבסוף, ה-PagingSource מבטל את עצמו, וה-Pager יוצר מופע חדש כדי לטעון את הנתונים החדשים ממסד הנתונים.

שימוש בסיסי

נניח שאתם רוצים שהאפליקציה תטען דפים של פריטי User ממקור נתונים ברשת עם מפתח פריט למטמון מקומי שמאוחסן במסד נתונים של Room.

‫RemoteMediator טוען נתונים מהרשת למסד הנתונים, ו-PagingSource טוען נתונים ממסד הנתונים. ‫Pager משתמש גם ב-RemoteMediator וגם ב-PagingSource כדי לטעון נתונים בדפים.
איור 3. תרשים של הטמעת Paging שמשתמשת במקור נתונים בשכבות.

הטמעה של RemoteMediator עוזרת לטעון נתונים מהרשת למסד הנתונים, אבל לא טוענת נתונים ישירות לממשק המשתמש. במקום זאת, האפליקציה משתמשת במסד הנתונים כמקור האמת. במילים אחרות, האפליקציה מציגה רק נתונים שנשמרו במטמון במסד הנתונים. הטמעה של PagingSource (לדוגמה, הטמעה שנוצרה על ידי Room) מטפלת בטעינת נתונים שנשמרו במטמון ממסד הנתונים לממשק המשתמש.

יצירת ישויות של חדרים

השלב הראשון הוא להשתמש בספריית Room persistence כדי להגדיר מסד נתונים שמכיל מטמון מקומי של נתונים מחולקים לדפים ממקור הנתונים ברשת. מתחילים בהטמעה של RoomDatabase, כמו שמתואר במאמר שמירת נתונים במסד נתונים מקומי באמצעות Room.

בשלב הבא, מגדירים ישות Room שתייצג טבלה של פריטים ברשימה, כמו שמתואר במאמר הגדרת נתונים באמצעות ישויות Room. נותנים לו שדה id כמפתח ראשי, וגם שדות לכל מידע אחר שהפריטים ברשימה מכילים.

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

צריך גם להגדיר אובייקט גישה לנתונים (DAO) לישות Room הזו, כמו שמתואר במאמר גישה לנתונים באמצעות אובייקטי גישה לנתונים של Room. ה-DAO של הישות של פריט הרשימה חייב לכלול את השיטות הבאות:

  • שיטת insertAll() שמכניסה רשימת פריטים לטבלה.
  • שיטה שמקבלת את מחרוזת השאילתה כפרמטר ומחזירה אובייקט PagingSource לרשימת התוצאות. כך אובייקט Pager יכול להשתמש בטבלה הזו כמקור לנתונים עם דפים.
  • שיטת 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();
}

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

הטמעה של RemoteMediator

התפקיד העיקרי של RemoteMediator הוא לטעון עוד נתונים מהרשת כשנגמרים הנתונים ב-Pager או כשהנתונים הקיימים לא תקפים. הוא כולל שיטה מסוג load() שצריך לשנות כדי להגדיר את אופן הטעינה.

הטמעה אופיינית של RemoteMediator כוללת את הפרמטרים הבאים:

  • ‫query: מחרוזת שאילתה שמגדירה אילו נתונים לאחזר משירות הקצה העורפי.
  • ‫database: מסד הנתונים של Room שמשמש כמטמון מקומי.
  • ‫networkService: מכונה של API לשירות לקצה העורפי.

יוצרים הטמעה של RemoteMediator<Key, Value>. הסוג של Key והסוג של Value צריכים להיות זהים לאלה שהייתם מגדירים ל-PagingSource באותו מקור נתונים ברשת. למידע נוסף על בחירת פרמטרים של סוגים, ראו בחירת סוגי מפתחות וערכים.

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

ה-method‏ load() אחראית לעדכון מערך הנתונים התומך ולביטול התוקף של PagingSource. חלק מהספריות שתומכות בדפדוף (כמו Room) יטפלו באופן אוטומטי בביטול התוקף של אובייקטים מסוג PagingSource שהן מטמיעות.

ה-method‏ load() מקבלת שני פרמטרים:

  • PagingState, שמכיל מידע על הדפים שנטענו עד עכשיו, האינדקס האחרון שאליו ניגשו והאובייקט PagingConfig שבו השתמשתם כדי להפעיל את זרם הדפים.
  • ‫LoadType, שמציין את סוג הטעינה: REFRESH,‏ APPEND או PREPEND.

הערך המוחזר של השיטה load() הוא אובייקט MediatorResult. הערך של MediatorResult יכול להיות MediatorResult.Error (שכולל את תיאור השגיאה) או MediatorResult.Success (שכולל אות שמציין אם יש עוד נתונים לטעון).

השיטה load() צריכה לבצע את השלבים הבאים:

  1. קובעים איזה דף לטעון מהרשת בהתאם לסוג הטעינה ולנתונים שנטענו עד עכשיו.
  2. מפעילים את הבקשה לאחזור מהרשת.
  3. מבצעים פעולות בהתאם לתוצאה של פעולת הטעינה:
    • אם הטעינה הצליחה ורשימת הפריטים שהתקבלה לא ריקה, שומרים את הפריטים ברשימה במסד הנתונים ומחזירים את הערך MediatorResult.Success(endOfPaginationReached = false). אחרי שהנתונים נשמרים, מבטלים את התוקף של מקור הנתונים כדי להודיע לספריית Paging על הנתונים החדשים.
    • אם הטעינה הצליחה ורשימת הפריטים שהתקבלה ריקה או שהיא אינדקס הדף האחרון, מחזירים את הערך MediatorResult.Success(endOfPaginationReached = true). אחרי שהנתונים נשמרים, מבטלים את התוקף של מקור הנתונים כדי להודיע לספריית Paging על הנתונים החדשים.
    • אם הבקשה גורמת לשגיאה, הפונקציה מחזירה את הערך MediatorResult.Error.

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

הגדרה של שיטת initialize

הטמעות של RemoteMediator יכולות גם לשנות את השיטה initialize() כדי לבדוק אם הנתונים שנשמרו במטמון לא עדכניים, ולהחליט אם להפעיל רענון מרחוק. השיטה הזו פועלת לפני שמתבצעת טעינה כלשהי, כך שאפשר לבצע שינויים במסד הנתונים (לדוגמה, כדי לנקות נתונים ישנים) לפני שמפעילים טעינות מקומיות או מרוחקות.

מכיוון ש-initialize() היא פונקציה אסינכרונית, אפשר לטעון נתונים כדי לקבוע את הרלוונטיות של הנתונים הקיימים במסד הנתונים. המקרה הנפוץ ביותר הוא שהנתונים שנשמרו במטמון תקפים רק לפרק זמן מסוים. ה-RemoteMediator יכול לבדוק אם זמן התפוגה הזה עבר, ובמקרה כזה ספריית Paging צריכה לרענן את הנתונים באופן מלא. הטמעות של initialize() צריכות להחזיר InitializeAction באופן הבא:

  • במקרים שבהם צריך לרענן את הנתונים מחנויות מקומיות באופן מלא, initialize() צריך להחזיר את הערך InitializeAction.LAUNCH_INITIAL_REFRESH. כתוצאה מכך, RemoteMediator מבצע רענון מרחוק כדי לטעון מחדש את הנתונים באופן מלא. כל טעינה מרחוק של APPEND או PREPEND ממתינה עד שהטעינה של REFRESH תסתיים בהצלחה לפני שהיא ממשיכה.
  • במקרים שבהם לא צריך לרענן את הנתונים מחנויות מקומיות, initialize() צריך להחזיר את הערך InitializeAction.SKIP_INITIAL_REFRESH. כתוצאה מכך, RemoteMediator מדלג על הרענון מרחוק וטוען את הנתונים מהמטמון.

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

יצירת כלי לדפדוף

לבסוף, צריך ליצור מופע של Pager כדי להגדיר את הסטרימינג של הנתונים המחולקים לדפים. התהליך דומה ליצירת Pager ממקור נתונים פשוט ברשת, אבל יש שני דברים שצריך לעשות אחרת:

  • במקום להעביר ישירות בנאי של PagingSource, צריך לספק את שיטת השאילתה שמחזירה אובייקט PagingSource מה-DAO.
  • אתם צריכים לספק מופע של ההטמעה של RemoteMediator בתור הפרמטר remoteMediator.

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

ניהול מפתחות לשליטה מרחוק

מפתחות מרוחקים הם מפתחות שבהם הטמעה של RemoteMediator משתמשת כדי להורות לשירות לקצה העורפי אילו נתונים לטעון בהמשך. במקרה הפשוט ביותר, כל פריט של נתונים בדפים כולל מפתח מרוחק שאפשר להפנות אליו בקלות. עם זאת, אם המפתחות המרוחקים לא תואמים לפריטים נפרדים, צריך לאחסן אותם בנפרד ולנהל אותם ב-method‏ load().

בקטע הזה מוסבר איך לאסוף, לאחסן ולעדכן מפתחות מרוחקים שלא מאוחסנים בפריטים בודדים.

מפתחות של פריטים

בקטע הזה מוסבר איך לעבוד עם מפתחות מרוחקים שתואמים לפריטים ספציפיים. בדרך כלל, כש-API מזהה פריטים ספציפיים, מזהה הפריט מועבר כפרמטר של שאילתה. שם הפרמטר מציין אם השרת צריך להגיב עם פריטים לפני או אחרי המזהה שצוין. בדוגמה של מחלקת המודל User, השדה id מהשרת משמש כמפתח מרוחק כשמבקשים נתונים נוספים.

כשה-method של load() צריך לנהל מפתחות מרוחקים ספציפיים לפריט, המפתחות האלה הם בדרך כלל המזהים של הנתונים שנשלפו מהשרת. בפעולות רענון לא צריך מפתח טעינה, כי הן רק מאחזרות את הנתונים העדכניים ביותר. באופן דומה, פעולות הוספה בתחילת הרשימה לא צריכות לאחזר נתונים נוספים כי הרענון תמיד שולף את הנתונים העדכניים ביותר מהשרת.

עם זאת, פעולות הוספה כן דורשות מזהה. לשם כך, צריך לטעון את הפריט האחרון ממסד הנתונים ולהשתמש במזהה שלו כדי לטעון את דף הנתונים הבא. אם אין פריטים במסד הנתונים, הערך של endOfPaginationReached מוגדר כ-true, מה שמציין שצריך לרענן את הנתונים.

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

מפתחות דפים

בקטע הזה מוסבר איך לעבוד עם מפתחות מרוחקים שלא תואמים לפריטים ספציפיים.

הוספת טבלת מפתחות מרוחקת

אם המפתחות המרוחקים לא משויכים ישירות לפריטים ברשימה, מומלץ לאחסן אותם בטבלה נפרדת במסד הנתונים המקומי. מגדירים ישות Room שמייצגת טבלה של מפתחות מרוחקים:

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

צריך גם להגדיר DAO לישות 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);
}

טעינה באמצעות מפתחות מרוחקים

כשה-method ‏load() צריך לנהל מפתחות של דפים מרוחקים, צריך להגדיר אותו באופן שונה בהשוואה לשימוש בסיסי ב-RemoteMediator:

  • מוסיפים עוד מאפיין שמכיל הפניה ל-DAO של טבלת המפתחות המרוחקים.
  • כדי לקבוע איזה מפתח לטעון, צריך לשלוח שאילתה לטבלת המפתחות המרוחקת במקום להשתמש ב-PagingState.
  • מוסיפים או מאחסנים את המפתח המרוחק שהוחזר ממקור הנתונים ברשת, בנוסף לנתונים שמוצגים בדף עצמו.

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

מקורות מידע נוספים

איפה אפשר למצוא מידע נוסף על ספריית Paging?

דוגמאות