مدیریت و ارائه حالت‌های بارگیری (نماها)

مفاهیم و پیاده‌سازی Jetpack Compose

کتابخانه «صفحه‌بندی» وضعیت درخواست‌های بارگیری را برای داده‌های صفحه‌بندی‌شده ردیابی می‌کند و آن را ازطریق کلاس LoadState نشان می‌دهد. برنامه شما می‌تواند شنونده‌ای را با PagingDataAdapter ثبت کند تا اطلاعات مربوط به وضعیت فعلی را دریافت کند و میانای کاربر را براساس آن به‌روز کند. این وضعیت‌ها از آداپتور ارائه می‌شوند زیرا با میانای کاربر همگام هستند. این یعنی شنونده شما وقتی به‌روزرسانی‌ها را دریافت می‌کند که بار کردن صفحه در میانای کاربر اعمال شده باشد.

سیگنال LoadState جداگانه‌ای برای هر LoadType و نوع منبع داده (PagingSource یا RemoteMediator) ارائه می‌شود. شیء CombinedLoadStates ارائه‌شده توسط شنونده اطلاعاتی درباره وضعیت بارگیری از همه این سیگنال‌ها ارائه می‌دهد. می‌توانید از این اطلاعات دقیق برای نمایش نشانگرهای بارگیری مناسب به کاربران استفاده کنید.

درحال بار کردن ایالت‌ها

کتابخانه Paging وضعیت بارگیری را برای استفاده در میانای کاربر ازطریق شیء LoadState نشان می‌دهد. LoadState اشیاء بسته به وضعیت بارگیری فعلی، یکی از سه شکل را به خود می‌گیرند:

  • اگر عملیات بارگیری فعالی وجود نداشته باشد و خطایی رخ نداده باشد، LoadState یک شیء LoadState.NotLoading است. این زیرکلاس همچنین شامل ویژگی endOfPaginationReached است که نشان می‌دهد آیا به پایان صفحه‌بندی رسیده‌ایم یا نه.
  • اگر عملیات بارگیری فعالی وجود داشته باشد، LoadState یک LoadState.Loading شیء است.
  • اگر خطایی وجود داشته باشد، LoadState یک شیء LoadState.Error است.

دو روش برای استفاده از LoadState در میانای کاربر وجود دارد: استفاده از شنونده، یا استفاده از آداپتور فهرست ویژه برای ارائه مستقیم وضعیت بارگیری در RecyclerView فهرست.

دسترسی به وضعیت بارگیری با شنونده

برای دریافت وضعیت بارگیری برای استفاده عمومی در میانای کاربر، از جاری‌سازی loadStateFlow یا روش addLoadStateListener() ارائه‌شده توسط PagingDataAdapter استفاده کنید. این سازوکارها دسترسی به شیء CombinedLoadStates را فراهم می‌کنند که شامل اطلاعاتی درباره رفتار LoadState برای هر نوع بارگیری است.

در مثال زیر، PagingDataAdapter مؤلفه‌های مختلف میانای کاربر را بسته به وضعیت فعلی بار بازآوری نمایش می‌دهد:

کاتلین

// Activities can use lifecycleScope directly, but Fragments should instead use
// viewLifecycleOwner.lifecycleScope.
lifecycleScope.launch {
  pagingAdapter.loadStateFlow.collectLatest { loadStates ->
    progressBar.isVisible = loadStates.refresh is LoadState.Loading
    retry.isVisible = loadState.refresh !is LoadState.Loading
    errorMsg.isVisible = loadState.refresh is LoadState.Error
  }
}

جاوا

pagingAdapter.addLoadStateListener(loadStates -> {
  progressBar.setVisibility(loadStates.refresh instanceof LoadState.Loading
    ? View.VISIBLE : View.GONE);
  retry.setVisibility(loadStates.refresh instanceof LoadState.Loading
    ? View.GONE : View.VISIBLE);
  errorMsg.setVisibility(loadStates.refresh instanceof LoadState.Error
    ? View.VISIBLE : View.GONE);
});

جاوا

pagingAdapter.addLoadStateListener(loadStates -> {
  progressBar.setVisibility(loadStates.refresh instanceof LoadState.Loading
    ? View.VISIBLE : View.GONE);
  retry.setVisibility(loadStates.refresh instanceof LoadState.Loading
    ? View.GONE : View.VISIBLE);
  errorMsg.setVisibility(loadStates.refresh instanceof LoadState.Error
    ? View.VISIBLE : View.GONE);
});

برای اطلاعات بیشتر درباره CombinedLoadStates، به دسترسی به اطلاعات بیشتر درباره وضعیت بار کردن مراجعه کنید.

ارائه وضعیت بارگیری با آداپتور

کتابخانه «صفحه‌بندی» آداپتور فهرست دیگری به‌نام LoadStateAdapter ارائه می‌دهد که هدف آن ارائه وضعیت بارگیری مستقیماً در فهرست نمایش‌داده‌شده داده‌های صفحه‌بندی‌شده است. این آداپتور دسترسی به وضعیت بارگیری فعلی فهرست را فراهم می‌کند، که می‌توانید آن را به نگهدارنده نمای سفارشی که اطلاعات را نمایش می‌دهد ارسال کنید.

ابتدا، یک کلاس نگهدارنده نما ایجاد کنید که ارجاع‌ها به نماهای بارگیری و خطا را در صفحه‌نمایش شما نگه می‌دارد. تابع bind() ایجاد کنید که LoadState را به‌عنوان پارامتر بپذیرد. این تابع باید رؤیت‌پذیری نما را براساس پارامتر وضعیت بارگیری تغییر دهد:

کاتلین

class LoadStateViewHolder(
  parent: ViewGroup,
  retry: () -> Unit
) : RecyclerView.ViewHolder(
  LayoutInflater.from(parent.context)
    .inflate(R.layout.load_state_item, parent, false)
) {
  private val binding = LoadStateItemBinding.bind(itemView)
  private val progressBar: ProgressBar = binding.progressBar
  private val errorMsg: TextView = binding.errorMsg
  private val retry: Button = binding.retryButton
    .also {
      it.setOnClickListener { retry() }
    }

  fun bind(loadState: LoadState) {
    if (loadState is LoadState.Error) {
      errorMsg.text = loadState.error.localizedMessage
    }

    progressBar.isVisible = loadState is LoadState.Loading
    retry.isVisible = loadState is LoadState.Error
    errorMsg.isVisible = loadState is LoadState.Error
  }
}

جاوا

class LoadStateViewHolder extends RecyclerView.ViewHolder {
  private ProgressBar mProgressBar;
  private TextView mErrorMsg;
  private Button mRetry;

  LoadStateViewHolder(
    @NonNull ViewGroup parent,
    @NonNull View.OnClickListener retryCallback) {
    super(LayoutInflater.from(parent.getContext())
      .inflate(R.layout.load_state_item, parent, false));

    LoadStateItemBinding binding = LoadStateItemBinding.bind(itemView);
    mProgressBar = binding.progressBar;
    mErrorMsg = binding.errorMsg;
    mRetry = binding.retryButton;
  }

  public void bind(LoadState loadState) {
    if (loadState instanceof LoadState.Error) {
      LoadState.Error loadStateError = (LoadState.Error) loadState;
      mErrorMsg.setText(loadStateError.getError().getLocalizedMessage());
    }
    mProgressBar.setVisibility(loadState instanceof LoadState.Loading
      ? View.VISIBLE : View.GONE);
    mRetry.setVisibility(loadState instanceof LoadState.Error
      ? View.VISIBLE : View.GONE);
    mErrorMsg.setVisibility(loadState instanceof LoadState.Error
      ? View.VISIBLE : View.GONE);
  }
}

جاوا

class LoadStateViewHolder extends RecyclerView.ViewHolder {
  private ProgressBar mProgressBar;
  private TextView mErrorMsg;
  private Button mRetry;

  LoadStateViewHolder(
    @NonNull ViewGroup parent,
    @NonNull View.OnClickListener retryCallback) {
    super(LayoutInflater.from(parent.getContext())
      .inflate(R.layout.load_state_item, parent, false));

    LoadStateItemBinding binding = LoadStateItemBinding.bind(itemView);
    mProgressBar = binding.progressBar;
    mErrorMsg = binding.errorMsg;
    mRetry = binding.retryButton;
  }

  public void bind(LoadState loadState) {
    if (loadState instanceof LoadState.Error) {
      LoadState.Error loadStateError = (LoadState.Error) loadState;
      mErrorMsg.setText(loadStateError.getError().getLocalizedMessage());
    }
    mProgressBar.setVisibility(loadState instanceof LoadState.Loading
      ? View.VISIBLE : View.GONE);
    mRetry.setVisibility(loadState instanceof LoadState.Error
      ? View.VISIBLE : View.GONE);
    mErrorMsg.setVisibility(loadState instanceof LoadState.Error
      ? View.VISIBLE : View.GONE);
  }
}

سپس، کلاسی ایجاد کنید که LoadStateAdapter را پیاده‌سازی کند و روش‌های onCreateViewHolder() و onBindViewHolder() را تعریف کنید. این روش‌ها نمونه‌ای از نگهدارنده نمای سفارشی شما را ایجاد می‌کنند و وضعیت بارگذاری مرتبط را مقید می‌کنند.

کاتلین

// Adapter that displays a loading spinner when
// state is LoadState.Loading, and an error message and retry
// button when state is LoadState.Error.
class ExampleLoadStateAdapter(
  private val retry: () -> Unit
) : LoadStateAdapter<LoadStateViewHolder>() {

  override fun onCreateViewHolder(
    parent: ViewGroup,
    loadState: LoadState
  ) = LoadStateViewHolder(parent, retry)

  override fun onBindViewHolder(
    holder: LoadStateViewHolder,
    loadState: LoadState
  ) = holder.bind(loadState)
}

جاوا

// Adapter that displays a loading spinner when
// state is LoadState.Loading, and an error message and retry
// button when state is LoadState.Error.
class ExampleLoadStateAdapter extends LoadStateAdapter<LoadStateViewHolder> {
  private View.OnClickListener mRetryCallback;

  ExampleLoadStateAdapter(View.OnClickListener retryCallback) {
    mRetryCallback = retryCallback;
  }

  @NotNull
  @Override
  public LoadStateViewHolder onCreateViewHolder(@NotNull ViewGroup parent,
    @NotNull LoadState loadState) {
    return new LoadStateViewHolder(parent, mRetryCallback);
  }

  @Override
  public void onBindViewHolder(@NotNull LoadStateViewHolder holder,
    @NotNull LoadState loadState) {
    holder.bind(loadState);
  }
}

جاوا

// Adapter that displays a loading spinner when
// state is LoadState.Loading, and an error message and retry
// button when state is LoadState.Error.
class ExampleLoadStateAdapter extends LoadStateAdapter<LoadStateViewHolder> {
  private View.OnClickListener mRetryCallback;

  ExampleLoadStateAdapter(View.OnClickListener retryCallback) {
    mRetryCallback = retryCallback;
  }

  @NotNull
  @Override
  public LoadStateViewHolder onCreateViewHolder(@NotNull ViewGroup parent,
    @NotNull LoadState loadState) {
    return new LoadStateViewHolder(parent, mRetryCallback);
  }

  @Override
  public void onBindViewHolder(@NotNull LoadStateViewHolder holder,
    @NotNull LoadState loadState) {
    holder.bind(loadState);
  }
}

برای نمایش پیشرفت بار کردن در سرصفحه و پاصفحه، withLoadStateHeaderAndFooter() را از شیء PagingDataAdapter فراخوانی کنید:

کاتلین

pagingAdapter
  .withLoadStateHeaderAndFooter(
    header = ExampleLoadStateAdapter(adapter::retry),
    footer = ExampleLoadStateAdapter(adapter::retry)
  )

جاوا

pagingAdapter
  .withLoadStateHeaderAndFooter(
    new ExampleLoadStateAdapter(pagingAdapter::retry),
    new ExampleLoadStateAdapter(pagingAdapter::retry));

جاوا

pagingAdapter
  .withLoadStateHeaderAndFooter(
    new ExampleLoadStateAdapter(pagingAdapter::retry),
    new ExampleLoadStateAdapter(pagingAdapter::retry));

درعوض می‌توانید withLoadStateHeader() یا withLoadStateFooter() را فراخوانی کنید اگر می‌خواهید فهرست RecyclerView وضعیت بار کردن را فقط در سرصفحه یا فقط در پاصفحه نمایش دهد.

دسترسی به اطلاعات بیشتر درباره وضعیت بارگیری

شیء CombinedLoadStates از PagingDataAdapter اطلاعاتی درباره وضعیت‌های بارگیری برای پیاده‌سازی PagingSource و همچنین برای پیاده‌سازی RemoteMediator (درصورت وجود) ارائه می‌دهد.

برای راحتی کار، می‌توانید از ویژگی‌های refresh، append، و prepend از CombinedLoadStates برای دسترسی به شیء LoadState برای نوع بارگیری مناسب استفاده کنید. این ویژگی‌ها معمولاً به حالت بارگیری از پیاده‌سازی RemoteMediator (درصورت وجود) ارجاع می‌دهند؛ درغیراین‌صورت، حاوی حالت بارگیری مناسب از پیاده‌سازی PagingSource هستند. برای اطلاعات دقیق‌تر درباره منطق اساسی، به اسناد مرجع CombinedLoadStates مراجعه کنید.

کاتلین

lifecycleScope.launch {
  pagingAdapter.loadStateFlow.collectLatest { loadStates ->
    // Observe refresh load state from RemoteMediator if present, or
    // from PagingSource otherwise.
    refreshLoadState: LoadState = loadStates.refresh
    // Observe prepend load state from RemoteMediator if present, or
    // from PagingSource otherwise.
    prependLoadState: LoadState = loadStates.prepend
    // Observe append load state from RemoteMediator if present, or
    // from PagingSource otherwise.
    appendLoadState: LoadState = loadStates.append
  }
}

جاوا

pagingAdapter.addLoadStateListener(loadStates -> {
  // Observe refresh load state from RemoteMediator if present, or
  // from PagingSource otherwise.
  LoadState refreshLoadState = loadStates.refresh;
  // Observe prepend load state from RemoteMediator if present, or
  // from PagingSource otherwise.
  LoadState prependLoadState = loadStates.prepend;
  // Observe append load state from RemoteMediator if present, or
  // from PagingSource otherwise.
  LoadState appendLoadState = loadStates.append;
});

جاوا

pagingAdapter.addLoadStateListener(loadStates -> {
  // Observe refresh load state from RemoteMediator if present, or
  // from PagingSource otherwise.
  LoadState refreshLoadState = loadStates.refresh;
  // Observe prepend load state from RemoteMediator if present, or
  // from PagingSource otherwise.
  LoadState prependLoadState = loadStates.prepend;
  // Observe append load state from RemoteMediator if present, or
  // from PagingSource otherwise.
  LoadState appendLoadState = loadStates.append;
});

بااین‌حال، مهم است به‌خاطر داشته باشید که فقط تضمین می‌شود که حالت‌های بارگیری PagingSource با به‌روزرسانی‌های میانای کاربر همگام باشند. چون ویژگی‌های refresh، append، و prepend می‌توانند به‌طور بالقوه وضعیت بارگیری را از PagingSource یا RemoteMediator بگیرند، تضمینی وجود ندارد که با به‌روزرسانی‌های میانای کاربر همگام باشند. این امر می‌تواند باعث بروز مشکلات میانای کاربر شود، به‌طوری‌که به‌نظر می‌رسد بار کردن قبل‌از اینکه داده‌های جدید به میانای کاربر اضافه شود تمام شده است.

به همین دلیل، دسترسی‌های راحتی برای نمایش وضعیت بارگذاری در سرصفحه یا پاصفحه به‌خوبی کار می‌کنند، اما برای موارد استفاده دیگر ممکن است نیاز داشته باشید به‌طور خاص از PagingSource یا RemoteMediator به وضعیت بارگذاری دسترسی پیدا کنید. CombinedLoadStates ویژگی‌های source و mediator را برای این منظور ارائه می‌دهد. هرکدام از این ویژگی‌ها یک شیء LoadStates را نشان می‌دهند که حاوی اشیاء LoadState برای PagingSource یا RemoteMediator به‌ترتیب است:

کاتلین

lifecycleScope.launch {
  pagingAdapter.loadStateFlow.collectLatest { loadStates ->
    // Directly access the RemoteMediator refresh load state.
    mediatorRefreshLoadState: LoadState? = loadStates.mediator.refresh
    // Directly access the RemoteMediator append load state.
    mediatorAppendLoadState: LoadState? = loadStates.mediator.append
    // Directly access the RemoteMediator prepend load state.
    mediatorPrependLoadState: LoadState? = loadStates.mediator.prepend
    // Directly access the PagingSource refresh load state.
    sourceRefreshLoadState: LoadState = loadStates.source.refresh
    // Directly access the PagingSource append load state.
    sourceAppendLoadState: LoadState = loadStates.source.append
    // Directly access the PagingSource prepend load state.
    sourcePrependLoadState: LoadState = loadStates.source.prepend
  }
}

جاوا

pagingAdapter.addLoadStateListener(loadStates -> {
  // Directly access the RemoteMediator refresh load state.
  LoadState mediatorRefreshLoadState = loadStates.mediator.refresh;
  // Directly access the RemoteMediator append load state.
  LoadState mediatorAppendLoadState = loadStates.mediator.append;
  // Directly access the RemoteMediator prepend load state.
  LoadState mediatorPrependLoadState = loadStates.mediator.prepend;
  // Directly access the PagingSource refresh load state.
  LoadState sourceRefreshLoadState = loadStates.source.refresh;
  // Directly access the PagingSource append load state.
  LoadState sourceAppendLoadState = loadStates.source.append;
  // Directly access the PagingSource prepend load state.
  LoadState sourcePrependLoadState = loadStates.source.prepend;
});

جاوا

pagingAdapter.addLoadStateListener(loadStates -> {
  // Directly access the RemoteMediator refresh load state.
  LoadState mediatorRefreshLoadState = loadStates.mediator.refresh;
  // Directly access the RemoteMediator append load state.
  LoadState mediatorAppendLoadState = loadStates.mediator.append;
  // Directly access the RemoteMediator prepend load state.
  LoadState mediatorPrependLoadState = loadStates.mediator.prepend;
  // Directly access the PagingSource refresh load state.
  LoadState sourceRefreshLoadState = loadStates.source.refresh;
  // Directly access the PagingSource append load state.
  LoadState sourceAppendLoadState = loadStates.source.append;
  // Directly access the PagingSource prepend load state.
  LoadState sourcePrependLoadState = loadStates.source.prepend;
});

اپراتورهای زنجیره‌ای در LoadState

ازآنجایی‌که شیء CombinedLoadStates دسترسی به همه تغییرات در وضعیت بارگیری را فراهم می‌کند، مهم است که جریان وضعیت بارگیری را براساس رویدادهای خاص فیلتر کنید. این کار تضمین می‌کند که میانای کاربر را در زمان مناسب به‌روز کنید تا از توقف و به‌روزرسانی‌های غیرضروری میانای کاربر جلوگیری شود.

برای مثال، فرض کنید می‌خواهید نمای خالی را نمایش دهید، اما فقط پس‌از تکمیل بارگیری داده‌های اولیه. این مورد استفاده مستلزم آن است که تأیید کنید بارگذاری بازآوری داده شروع شده است، سپس منتظر حالت NotLoading بمانید تا تأیید شود که بازآوری تکمیل شده است. باید همه سیگنال‌ها را به‌جز سیگنال‌هایی که نیاز دارید فیلتر کنید:

کاتلین

lifecycleScope.launchWhenCreated {
  adapter.loadStateFlow
    // Only emit when REFRESH LoadState for RemoteMediator changes.
    .distinctUntilChangedBy { it.refresh }
    // Only react to cases where REFRESH completes, such as NotLoading.
    .filter { it.refresh is LoadState.NotLoading }
    // Scroll to top is synchronous with UI updates, even if remote load was
    // triggered.
    .collect { binding.list.scrollToPosition(0) }
}

جاوا

PublishSubject<CombinedLoadStates> subject = PublishSubject.create();
Disposable disposable =
  subject.distinctUntilChanged(CombinedLoadStates::getRefresh)
  .filter(
    combinedLoadStates -> combinedLoadStates.getRefresh() instanceof LoadState.NotLoading)
  .subscribe(combinedLoadStates -> binding.list.scrollToPosition(0));

pagingAdapter.addLoadStateListener(loadStates -> {
  subject.onNext(loadStates);
});

جاوا

LiveData<CombinedLoadStates> liveData = new MutableLiveData<>();
LiveData<LoadState> refreshLiveData =
  Transformations.map(liveData, CombinedLoadStates::getRefresh);
LiveData<LoadState> distinctLiveData =
  Transformations.distinctUntilChanged(refreshLiveData);

distinctLiveData.observeForever(loadState -> {
  if (loadState instanceof LoadState.NotLoading) {
    binding.list.scrollToPosition(0);
  }
});

این مثال تا زمانی‌که وضعیت بارگذاری بازآوری به‌روز شود منتظر می‌ماند، اما فقط زمانی راه‌اندازی می‌شود که وضعیت NotLoading باشد. این کار تضمین می‌کند که بازآوری ازراه‌دور کاملاً تمام شده است قبل‌از اینکه هرگونه به‌روزرسانی میانای کاربر اتفاق بیفتد.

میاناهای برنامه‌سازی کاربردی جاری‌سازی این نوع عملیات را ممکن می‌سازند. برنامه شما می‌تواند رویدادهای بارگیری موردنیازش را مشخص کند و وقتی معیارهای مناسب برآورده شد، داده‌های جدید را مدیریت کند.