Я использую библиотеку подкачки Android для отображения списка данных во фрагменте. Это работает, но когда я поворачиваю экран, список загружается заново вместо уже загруженных данных.
Я сделал это для этой статьи. В чем проблема?
Это мой RxPagingSource
public Single loadSingle(@NotNull LoadParams loadParams) {
Integer nextPageNumber = loadParams.getKey();
if (nextPageNumber == null) {
nextPageNumber = 1;
}
return dataApi.getBooksCatalog(nextPageNumber, new ArrayMap(), preferencesHelper.auth())
.subscribeOn(Schedulers.io())
.map(this::toLoadResult)
.onErrorReturn(LoadResult.Error::new);
}
private LoadResult toLoadResult(ResponseData response) {
int currentPage = response.getData().getCurrentPage();
return new LoadResult.Page(
response.getData().getData(),
currentPage > 1 ? currentPage - 1 : null,
response.getData().getData().isEmpty() ? null : currentPage + 1);
}
public Integer getRefreshKey(@NotNull PagingState pagingState) {
Integer anchorPosition = pagingState.getAnchorPosition();
if (anchorPosition == null) {
return null;
}
LoadResult.Page anchorPage = pagingState.closestPageToPosition(anchorPosition);
if (anchorPage == null) {
return null;
}
Integer prevKey = anchorPage.getPrevKey();
if (prevKey != null) {
return prevKey + 1;
}
Integer nextKey = anchorPage.getNextKey();
if (nextKey != null) {
return nextKey - 1;
}
return null;
}
Я не понял, в каком случае следует вызывать метод getRefreshKey().
PagingDataAdapter и DiffUtil.ItemCallback являются стандартными ...
В моей ViewModel
@HiltViewModel
public class BooksViewModel extends BaseDisposablesViewModel {
PagingConfig pagingConfig = new PagingConfig(50, 25, true, 100, 200);
private final DataApiInterface dataApi;
private final SharedPreferencesHelper preferencesHelper;
Flowable
> flowable;
@Inject
BooksViewModel(DataApiInterface dataApi, SharedPreferencesHelper preferencesHelper) {
this.dataApi = dataApi;
this.preferencesHelper = preferencesHelper;
init();
}
private void init() {
CoroutineScope viewModelScope = ViewModelKt.getViewModelScope(this);
Pager pager = new Pager(
pagingConfig,
() -> new BooksPagingSource(dataApi, preferencesHelper)
);
flowable = PagingRx.getFlowable(pager);
PagingRx.cachedIn(flowable, viewModelScope);
}
}
И мой фрагмент...
@AndroidEntryPoint
public class BooksFragment extends BaseFragment {
private FragmentBooksBinding binding;
private final CompositeDisposable disposable = new CompositeDisposable();
private BooksPagingAdapter pagingAdapter;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BooksViewModel viewModel = new ViewModelProvider(requireActivity()).get(BooksViewModel.class);
pagingAdapter = new BooksPagingAdapter(new BooksPagingAdapter.BookComparator());
disposable.add(viewModel.flowable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(bookPagingData -> pagingAdapter.submitData(getLifecycle(), bookPagingData)));
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
binding = FragmentBooksBinding.inflate(inflater, container, false);
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
binding.list.setAdapter(pagingAdapter);
}
@Override
public void onDestroy() {
super.onDestroy();
disposable.clear();
}
}
Подробнее здесь: https://stackoverflow.com/questions/699 ... ate-screen
RecyclerView перезагрузит данные при воссоздании активности/фрагмента (поворот экрана) ⇐ JAVA
Программисты JAVA общаются здесь
1727428156
Anonymous
Я использую библиотеку подкачки Android для отображения списка данных во фрагменте. Это работает, но когда я поворачиваю экран, список загружается заново вместо уже загруженных данных.
Я сделал это для этой статьи. В чем проблема?
Это мой RxPagingSource
public Single loadSingle(@NotNull LoadParams loadParams) {
Integer nextPageNumber = loadParams.getKey();
if (nextPageNumber == null) {
nextPageNumber = 1;
}
return dataApi.getBooksCatalog(nextPageNumber, new ArrayMap(), preferencesHelper.auth())
.subscribeOn(Schedulers.io())
.map(this::toLoadResult)
.onErrorReturn(LoadResult.Error::new);
}
private LoadResult toLoadResult(ResponseData response) {
int currentPage = response.getData().getCurrentPage();
return new LoadResult.Page(
response.getData().getData(),
currentPage > 1 ? currentPage - 1 : null,
response.getData().getData().isEmpty() ? null : currentPage + 1);
}
public Integer getRefreshKey(@NotNull PagingState pagingState) {
Integer anchorPosition = pagingState.getAnchorPosition();
if (anchorPosition == null) {
return null;
}
LoadResult.Page anchorPage = pagingState.closestPageToPosition(anchorPosition);
if (anchorPage == null) {
return null;
}
Integer prevKey = anchorPage.getPrevKey();
if (prevKey != null) {
return prevKey + 1;
}
Integer nextKey = anchorPage.getNextKey();
if (nextKey != null) {
return nextKey - 1;
}
return null;
}
Я не понял, в каком случае следует вызывать метод getRefreshKey().
PagingDataAdapter и DiffUtil.ItemCallback являются стандартными ...
В моей ViewModel
@HiltViewModel
public class BooksViewModel extends BaseDisposablesViewModel {
PagingConfig pagingConfig = new PagingConfig(50, 25, true, 100, 200);
private final DataApiInterface dataApi;
private final SharedPreferencesHelper preferencesHelper;
Flowable
> flowable;
@Inject
BooksViewModel(DataApiInterface dataApi, SharedPreferencesHelper preferencesHelper) {
this.dataApi = dataApi;
this.preferencesHelper = preferencesHelper;
init();
}
private void init() {
CoroutineScope viewModelScope = ViewModelKt.getViewModelScope(this);
Pager pager = new Pager(
pagingConfig,
() -> new BooksPagingSource(dataApi, preferencesHelper)
);
flowable = PagingRx.getFlowable(pager);
PagingRx.cachedIn(flowable, viewModelScope);
}
}
И мой фрагмент...
@AndroidEntryPoint
public class BooksFragment extends BaseFragment {
private FragmentBooksBinding binding;
private final CompositeDisposable disposable = new CompositeDisposable();
private BooksPagingAdapter pagingAdapter;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BooksViewModel viewModel = new ViewModelProvider(requireActivity()).get(BooksViewModel.class);
pagingAdapter = new BooksPagingAdapter(new BooksPagingAdapter.BookComparator());
disposable.add(viewModel.flowable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(bookPagingData -> pagingAdapter.submitData(getLifecycle(), bookPagingData)));
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
binding = FragmentBooksBinding.inflate(inflater, container, false);
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
binding.list.setAdapter(pagingAdapter);
}
@Override
public void onDestroy() {
super.onDestroy();
disposable.clear();
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/69910188/recyclerview-reload-data-on-activity-frgment-re-createrotate-screen[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия