เปลี่ยนรูปแบบสตรีมข้อมูล (มุมมอง)

แนวคิดและการใช้งาน Jetpack Compose

เมื่อทำงานกับข้อมูลที่มีการแบ่งหน้า คุณมักจะต้องเปลี่ยนรูปแบบสตรีมข้อมูลขณะโหลด เช่น คุณอาจต้องกรองรายการ หรือแปลงรายการเป็นประเภทอื่นก่อนที่จะแสดงใน UI กรณีการใช้งานทั่วไปอีกกรณีหนึ่งสำหรับการเปลี่ยนรูปแบบสตรีมข้อมูลคือการเพิ่มตัวคั่นรายการ

โดยทั่วไปแล้ว การใช้การเปลี่ยนรูปแบบกับสตรีมข้อมูลโดยตรงจะช่วยให้คุณแยกโครงสร้างที่เก็บข้อมูลและโครงสร้าง UI ออกจากกันได้

หน้านี้ถือว่าคุณคุ้นเคยกับการใช้งานพื้นฐานของไลบรารี Paging

ใช้การแปลงพื้นฐาน

เนื่องจาก PagingData อยู่ในสตรีมแบบรีแอ็กทีฟ คุณจึงใช้การดำเนินการเปลี่ยนรูปแบบกับข้อมูลแบบเพิ่มทีละน้อยระหว่างการโหลดข้อมูลและการนำเสนอข้อมูลได้

หากต้องการใช้การเปลี่ยนรูปแบบกับออบเจ็กต์ PagingData แต่ละรายการในสตรีม ให้วางการเปลี่ยนรูปแบบไว้ในการดำเนินการ map() ในสตรีม ดังนี้

Java

PagingRx.getFlowable(pager) // Type is Flowable<PagingData<User>>.
  // Map the outer stream so that the transformations are applied to
  // each new generation of PagingData.
  .map(pagingData -> {
    // Transformations in this block are applied to the items
    // in the paged data.
  });

Java

// Map the outer stream so that the transformations are applied to
// each new generation of PagingData.
Transformations.map(
  // Type is LiveData<PagingData<User>>.
  PagingLiveData.getLiveData(pager),
  pagingData -> {
    // Transformations in this block are applied to the items
    // in the paged data.
  });

แปลงข้อมูล

การดำเนินการขั้นพื้นฐานที่สุดในสตรีมข้อมูลคือการแปลงเป็นประเภทอื่น เมื่อเข้าถึงออบเจ็กต์ PagingData ได้แล้ว คุณจะดำเนินการ map() กับแต่ละรายการในรายการที่มีการแบ่งหน้าภายในออบเจ็กต์ PagingData ได้

กรณีการใช้งานที่พบบ่อยอย่างหนึ่งคือการแมปออบเจ็กต์เลเยอร์เครือข่ายหรือฐานข้อมูลกับออบเจ็กต์ที่ใช้ในเลเยอร์ UI โดยเฉพาะ ตัวอย่างด้านล่างแสดงวิธีใช้การดำเนินการกับแผนที่ประเภทนี้

Java

// Type is Flowable<PagingData<User>>.
PagingRx.getFlowable(pager)
  .map(pagingData ->
    pagingData.map(UiModel.UserModel::new)
  )

Java

Transformations.map(
  // Type is LiveData<PagingData<User>>.
  PagingLiveData.getLiveData(pager),
  pagingData ->
    pagingData.map(UiModel.UserModel::new)
)

การแปลงข้อมูลที่พบบ่อยอีกอย่างหนึ่งคือการรับอินพุตจากผู้ใช้ เช่น สตริงการค้นหา และแปลงเป็นเอาต์พุตคำขอเพื่อแสดงผล การตั้งค่านี้ต้องมีการฟังและบันทึกอินพุตคำค้นหาของผู้ใช้ ดำเนินการตามคำขอ และพุชผลการค้นหากลับไปยัง UI

คุณสามารถฟังอินพุตคำค้นหาได้โดยใช้ Stream API เก็บข้อมูลอ้างอิงสตรีมไว้ใน ViewModel เลเยอร์ UI ไม่ควรเข้าถึงโดยตรง แต่ให้กำหนดฟังก์ชันเพื่อแจ้ง ViewModel เกี่ยวกับคำค้นหาของผู้ใช้แทน

Java

private BehaviorSubject<String> querySubject = BehaviorSubject.create("");

public void onQueryChanged(String query) {
  queryFlow.onNext(query)
}

Java

private MutableLiveData<String> queryLiveData = new MutableLiveData("");

public void onQueryChanged(String query) {
  queryFlow.setValue(query)
}

เมื่อค่าการค้นหาเปลี่ยนแปลงในสตรีมข้อมูล คุณสามารถดำเนินการเพื่อแปลงค่าการค้นหาเป็นประเภทข้อมูลที่ต้องการและแสดงผลลัพธ์ไปยังเลเยอร์ UI ได้ ฟังก์ชันการแปลงที่เฉพาะเจาะจงจะขึ้นอยู่กับภาษาและเฟรมเวิร์กที่ใช้ แต่ทั้งหมดจะมีฟังก์ชันการทำงานที่คล้ายกัน

Java

Observable<User> querySearchResults =
  querySubject.switchMap(query -> userDatabase.searchBy(query));

Java

LiveData<User> querySearchResults = Transformations.switchMap(
  queryLiveData,
  query -> userDatabase.searchBy(query)
);

การใช้การดำเนินการอย่าง flatMapLatest หรือ switchMap จะช่วยให้มั่นใจได้ว่าระบบจะแสดงเฉพาะผลลัพธ์ล่าสุดใน UI หากผู้ใช้เปลี่ยนอินพุตการค้นหาก่อนที่การดำเนินการฐานข้อมูลจะเสร็จสมบูรณ์ การดำเนินการเหล่านี้จะทิ้งผลลัพธ์จากการค้นหาเก่าและเริ่มการค้นหาใหม่ทันที

ข้อมูลตัวกรอง

การดำเนินการทั่วไปอีกอย่างหนึ่งคือการกรอง คุณสามารถกรองข้อมูลตามเกณฑ์จากผู้ใช้ หรือจะนำข้อมูลออกจาก UI หากควรซ่อนตามเกณฑ์อื่นๆ ก็ได้

คุณต้องวางการดำเนินการตัวกรองเหล่านี้ไว้ในการเรียก map() เนื่องจากตัวกรองจะใช้กับออบเจ็กต์ PagingData เมื่อกรองข้อมูลออกจาก PagingData แล้ว ระบบจะส่งอินสแตนซ์ PagingData ใหม่ไปยังเลเยอร์ UI เพื่อแสดงผล

Java

// Type is Flowable<PagingData<User>>.
PagingRx.getFlowable(pager)
  .map(pagingData ->
    pagingData.filter(user -> !user.isHiddenFromUi())
  )
}

Java

Transformations.map(
  // Type is LiveData<PagingData<User>>.
  PagingLiveData.getLiveData(pager),
  pagingData ->
    pagingData.filter(user -> !user.isHiddenFromUi())
)

เพิ่มตัวคั่นรายการ

ไลบรารี Paging รองรับตัวคั่นรายการแบบไดนามิก คุณสามารถปรับปรุงความสามารถในการอ่านรายการได้โดยการแทรกตัวคั่นลงในสตรีมข้อมูลโดยตรงเป็นรายการ RecyclerView ด้วยเหตุนี้ ตัวคั่นจึงเป็นออบเจ็กต์ ViewHolder ที่มีฟีเจอร์ครบครัน ซึ่งช่วยให้สามารถโต้ตอบ โฟกัสการช่วยเหลือพิเศษ และฟีเจอร์อื่นๆ ทั้งหมดที่ View มีให้

การแทรกตัวคั่นลงในรายการที่มีการแบ่งหน้ามี 3 ขั้นตอนดังนี้

  1. แปลงโมเดล UI เพื่อรองรับรายการตัวคั่น
  2. เปลี่ยนรูปแบบสตรีมข้อมูลเพื่อเพิ่มตัวคั่นแบบไดนามิกระหว่างการโหลดข้อมูลและการแสดงข้อมูล
  3. อัปเดต UI เพื่อจัดการรายการตัวคั่น

แปลงโมเดล UI

ไลบรารี Paging จะแทรกตัวคั่นรายการลงใน RecyclerView เป็นรายการ จริง แต่รายการตัวคั่นต้องแยกความแตกต่างจากรายการข้อมูล ในรายการได้ เพื่อให้สามารถเชื่อมโยงกับประเภท ViewHolder อื่นที่มี UI ที่แตกต่างกัน วิธีแก้ปัญหาคือสร้าง Kotlin sealed class ที่มีคลาสย่อยเพื่อแสดงข้อมูลและตัวคั่น หรือจะสร้างคลาสพื้นฐานที่ขยายโดยคลาสรายการในลิสต์และคลาสตัวคั่นก็ได้

สมมติว่าคุณต้องการเพิ่มตัวคั่นลงในรายการที่มีการแบ่งหน้าซึ่งมี User รายการ ข้อมูลโค้ดต่อไปนี้แสดงวิธีสร้างคลาสพื้นฐานที่อินสแตนซ์เป็น UserModel หรือ SeparatorModel ก็ได้

Java

class UiModel {
  private UiModel() {}

  static class UserModel extends UiModel {
    @NonNull
    private String mId;
    @NonNull
    private String mLabel;

    UserModel(@NonNull String id, @NonNull String label) {
      mId = id;
      mLabel = label;
    }

    UserModel(@NonNull User user) {
      mId = user.id;
      mLabel = user.label;
    }

    @NonNull
    public String getId() {
      return mId;
    }

    @NonNull
    public String getLabel() {
      return mLabel;
      }
    }

    static class SeparatorModel extends UiModel {
    @NonNull
    private String mDescription;

    SeparatorModel(@NonNull String description) {
      mDescription = description;
    }

    @NonNull
    public String getDescription() {
      return mDescription;
    }
  }
}

Java

class UiModel {
  private UiModel() {}

  static class UserModel extends UiModel {
    @NonNull
    private String mId;
    @NonNull
    private String mLabel;

    UserModel(@NonNull String id, @NonNull String label) {
      mId = id;
      mLabel = label;
    }

    UserModel(@NonNull User user) {
      mId = user.id;
      mLabel = user.label;
    }

    @NonNull
    public String getId() {
      return mId;
    }

    @NonNull
    public String getLabel() {
      return mLabel;
      }
    }

    static class SeparatorModel extends UiModel {
    @NonNull
    private String mDescription;

    SeparatorModel(@NonNull String description) {
      mDescription = description;
    }

    @NonNull
    public String getDescription() {
      return mDescription;
    }
  }
}

เปลี่ยนรูปแบบสตรีมข้อมูล

คุณต้องใช้การเปลี่ยนรูปแบบกับสตรีมข้อมูลหลังจากโหลดและก่อนนำเสนอ การเปลี่ยนรูปแบบควรทำสิ่งต่อไปนี้

  • แปลงรายการที่โหลดเพื่อแสดงประเภทรายการฐานใหม่
  • ใช้เมธอด PagingData.insertSeparators() เพื่อเพิ่มตัวคั่น

ดูข้อมูลเพิ่มเติมเกี่ยวกับการดำเนินการเปลี่ยนรูปแบบได้ที่ใช้การเปลี่ยนรูปแบบพื้นฐาน

ตัวอย่างต่อไปนี้แสดงการดำเนินการเปลี่ยนรูปแบบเพื่ออัปเดตสตรีม PagingData<User> เป็นสตรีม PagingData<UiModel> โดยเพิ่มตัวคั่น

Java

// Map outer stream, so you can perform transformations on each
// paging generation.
PagingRx.getFlowable(pager).map(pagingData -> {
  // First convert items in stream to UiModel.UserModel.
  PagingData<UiModel> uiModelPagingData = pagingData.map(
    UiModel.UserModel::new);

  // Insert UiModel.SeparatorModel, which produces PagingData of
  // generic type UiModel.
  return PagingData.insertSeparators(uiModelPagingData,
    (@Nullable UiModel before, @Nullable UiModel after) -> {
      if (before == null) {
        return new UiModel.SeparatorModel("HEADER");
      } else if (after == null) {
        return new UiModel.SeparatorModel("FOOTER");
      } else if (shouldSeparate(before, after)) {
        return new UiModel.SeparatorModel("BETWEEN ITEMS "
          + before.toString() + " AND " + after.toString());
      } else {
        // Return null to avoid adding a separator between two
        // items.
        return null;
      }
    });
});

Java

// Map outer stream, so you can perform transformations on each
// paging generation.
Transformations.map(PagingLiveData.getLiveData(pager),
  pagingData -> {
    // First convert items in stream to UiModel.UserModel.
    PagingData<UiModel> uiModelPagingData = pagingData.map(
      UiModel.UserModel::new);

    // Insert UiModel.SeparatorModel, which produces PagingData of
    // generic type UiModel.
    return PagingData.insertSeparators(uiModelPagingData,
      (@Nullable UiModel before, @Nullable UiModel after) -> {
        if (before == null) {
          return new UiModel.SeparatorModel("HEADER");
        } else if (after == null) {
          return new UiModel.SeparatorModel("FOOTER");
        } else if (shouldSeparate(before, after)) {
          return new UiModel.SeparatorModel("BETWEEN ITEMS "
            + before.toString() + " AND " + after.toString());
        } else {
          // Return null to avoid adding a separator between two
          // items.
          return null;
        }
      });
  });

จัดการตัวคั่นใน UI

ขั้นตอนสุดท้ายคือการเปลี่ยน UI เพื่อรองรับประเภทรายการตัวคั่น สร้างเลย์เอาต์และ View Holder สำหรับรายการตัวคั่น และเปลี่ยน List Adapter ให้ใช้ RecyclerView.ViewHolder เป็นประเภท View Holder เพื่อให้จัดการ View Holder ได้มากกว่า 1 ประเภท หรือจะกำหนดคลาสพื้นฐานทั่วไปที่ทั้งคลาสตัวยึดมุมมองรายการและตัวคั่นขยายก็ได้

นอกจากนี้ คุณยังต้องทำการเปลี่ยนแปลงต่อไปนี้กับ List Adapter ด้วย

  • เพิ่มเคสลงในเมธอด onCreateViewHolder() และ onBindViewHolder() เพื่อพิจารณารายการตัวคั่น
  • ใช้ตัวเปรียบเทียบใหม่

Java

class UiModelAdapter extends PagingDataAdapter<UiModel, RecyclerView.ViewHolder> {
  UiModelAdapter() {
    super(new UiModelComparator(), Dispatchers.getMain(),
      Dispatchers.getDefault());
  }

  @NonNull
  @Override
  public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent,
    int viewType) {
    if (viewType == R.layout.item) {
      return new UserModelViewHolder(parent);
    } else {
      return new SeparatorModelViewHolder(parent);
    }
  }

  @Override
  public int getItemViewType(int position) {
    // Use peek over getItem to avoid triggering page fetch / drops, since
    // recycling views is not indicative of the user's current scroll position.
    UiModel item = peek(position);
    if (item instanceof UiModel.UserModel) {
      return R.layout.item;
    } else if (item instanceof UiModel.SeparatorModel) {
      return R.layout.separator_item;
    } else {
      throw new IllegalStateException("Unknown view");
    }
  }

  @Override
  public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder,
    int position) {
    if (holder instanceOf UserModelViewHolder) {
      UserModel userModel = (UserModel) getItem(position);
      ((UserModelViewHolder) holder).bind(userModel);
    } else {
      SeparatorModel separatorModel = (SeparatorModel) getItem(position);
      ((SeparatorModelViewHolder) holder).bind(separatorModel);
    }
  }
}

class UiModelComparator extends DiffUtil.ItemCallback<UiModel> {
  @Override
  public boolean areItemsTheSame(@NonNull UiModel oldItem,
    @NonNull UiModel newItem) {
    boolean isSameRepoItem = oldItem instanceof UserModel
      && newItem instanceof UserModel
      && ((UserModel) oldItem).getId().equals(((UserModel) newItem).getId());

    boolean isSameSeparatorItem = oldItem instanceof SeparatorModel
      && newItem instanceof SeparatorModel
      && ((SeparatorModel) oldItem).getDescription().equals(
      ((SeparatorModel) newItem).getDescription());

    return isSameRepoItem || isSameSeparatorItem;
  }

  @Override
  public boolean areContentsTheSame(@NonNull UiModel oldItem,
    @NonNull UiModel newItem) {
    return oldItem.equals(newItem);
  }
}

Java

class UiModelAdapter extends PagingDataAdapter<UiModel, RecyclerView.ViewHolder> {
  UiModelAdapter() {
    super(new UiModelComparator(), Dispatchers.getMain(),
      Dispatchers.getDefault());
  }

  @NonNull
  @Override
  public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent,
    int viewType) {
    if (viewType == R.layout.item) {
      return new UserModelViewHolder(parent);
    } else {
      return new SeparatorModelViewHolder(parent);
    }
  }

  @Override
  public int getItemViewType(int position) {
    // Use peek over getItem to avoid triggering page fetch / drops, since
    // recycling views is not indicative of the user's current scroll position.
    UiModel item = peek(position);
    if (item instanceof UiModel.UserModel) {
      return R.layout.item;
    } else if (item instanceof UiModel.SeparatorModel) {
      return R.layout.separator_item;
    } else {
      throw new IllegalStateException("Unknown view");
    }
  }

  @Override
  public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder,
    int position) {
    if (holder instanceOf UserModelViewHolder) {
      UserModel userModel = (UserModel) getItem(position);
      ((UserModelViewHolder) holder).bind(userModel);
    } else {
      SeparatorModel separatorModel = (SeparatorModel) getItem(position);
      ((SeparatorModelViewHolder) holder).bind(separatorModel);
    }
  }
}

class UiModelComparator extends DiffUtil.ItemCallback<UiModel> {
  @Override
  public boolean areItemsTheSame(@NonNull UiModel oldItem,
    @NonNull UiModel newItem) {
    boolean isSameRepoItem = oldItem instanceof UserModel
      && newItem instanceof UserModel
      && ((UserModel) oldItem).getId().equals(((UserModel) newItem).getId());

    boolean isSameSeparatorItem = oldItem instanceof SeparatorModel
      && newItem instanceof SeparatorModel
      && ((SeparatorModel) oldItem).getDescription().equals(
      ((SeparatorModel) newItem).getDescription());

    return isSameRepoItem || isSameSeparatorItem;
  }

  @Override
  public boolean areContentsTheSame(@NonNull UiModel oldItem,
    @NonNull UiModel newItem) {
    return oldItem.equals(newItem);
  }
}

หลีกเลี่ยงการทำงานซ้ำซ้อน

ปัญหาสำคัญอย่างหนึ่งที่ควรหลีกเลี่ยงคือการให้แอปทำงานที่ไม่จำเป็น การดึงข้อมูลเป็นการดำเนินการที่มีค่าใช้จ่ายสูง และการเปลี่ยนรูปแบบข้อมูลก็อาจใช้เวลาอันมีค่าด้วย เมื่อโหลดข้อมูลและเตรียมพร้อมสำหรับการแสดงผลใน UI แล้ว ควรบันทึกข้อมูลไว้ในกรณีที่มีการเปลี่ยนแปลงการกำหนดค่าและจำเป็นต้องสร้าง UI ใหม่

การดำเนินการ cachedIn() จะแคชผลลัพธ์ของการเปลี่ยนรูปแบบที่เกิดขึ้นก่อนหน้า ดังนั้น cachedIn() ควรเป็นการเรียกใช้ครั้งสุดท้ายใน ViewModel

Java

// CoroutineScope helper provided by the lifecycle-viewmodel-ktx artifact.
CoroutineScope viewModelScope = ViewModelKt.getViewModelScope(viewModel);
PagingRx.cachedIn(
  // Type is Flowable<PagingData<User>>.
  PagingRx.getFlowable(pager)
    .map(pagingData -> pagingData
      .filter(user -> !user.isHiddenFromUi())
      .map(UiModel.UserModel::new)),
  viewModelScope);
}

Java

// CoroutineScope helper provided by the lifecycle-viewmodel-ktx artifact.
CoroutineScope viewModelScope = ViewModelKt.getViewModelScope(viewModel);
PagingLiveData.cachedIn(
  Transformations.map(
    // Type is LiveData<PagingData<User>>.
    PagingLiveData.getLiveData(pager),
    pagingData -> pagingData
      .filter(user -> !user.isHiddenFromUi())
      .map(UiModel.UserModel::new)),
  viewModelScope);

ดูข้อมูลเพิ่มเติมเกี่ยวกับการใช้ cachedIn() กับสตรีมของ PagingData ได้ที่ตั้งค่าสตรีมของ PagingData