gpt4 book ai didi

android - RecyclerView 使用 RxJava 无限滚动

转载 作者:塔克拉玛干 更新时间:2023-11-02 18:55:31 27 4
gpt4 key购买 nike

我想使用 RxJava 在 RecyclerView 上实现 Endless Scrolling 功能。

我想要什么:我想从 API 调用中获取前 10 个数据并将其显示在 RecyclerView 中。用户向下滚动这 10 个数据后,我想进行另一个 API 调用并提取另外 10 个数据。再次当用户在这些最新的 10 个数据之后向下滚动时,我必须为另外 10 个数据进行 API 调用。这将一直持续到 API 调用提供所有数据为止。

我尝试使用 take 运算符,但没有得到想要的结果。我搜索了不同的运营商,但没有找到单个运营商或运营商的任何组合来实现这一目标。任何帮助将不胜感激。

我的代码如下。

SalesDashboardActivity.java

    public class SalesDashboardActivity2 extends BaseActivity implements SalesDashboardView {

List<DashboardStatusBean> inProgressList = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sales_dashboard2);
ButterKnife.bind(this);
setSupportActionBar(mToolbar);
mSalesDashboardPresenter.attachView(this);
getDashboardData();
}

private void getDashboardData() {

SearchLoansInput searchLoansInput = new SearchLoansInput();
searchLoansInput.setUserName(sessionManager.getMobileNumber());

if (Util.isInternetConnection(this)) {
mSalesDashboardPresenter.handleSalesInquiryRequest(searchLoansInput);
} else {
displayToastMessage("Internet is not available! Check your internet connection.");
}
}

@Override
public void handleSalesInquiryResponse(SearchLoansOutput searchLoansOutputData) {

if (searchLoansOutputData.isSuccess()) {

Util.SALES_IN_PROGRESS_LIST.clear();

for (int i = 0; i < searchLoansOutputData.getLoanDetailList().size(); i++) {
DashboardStatusBean dashboardStatusBean = new DashboardStatusBean();
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy");
String approveDate = null;
String createdDate = null;

if (searchLoansOutputData.getLoanDetailList().get(i).getCreatedDate() != null) {
createdDate = String.valueOf(sdf.format(searchLoansOutputData.getLoanDetailList().get(i).getCreatedDate()));
}
if (searchLoansOutputData.getLoanDetailList().get(i).getApprovedDate() != null) {
approveDate = String.valueOf(sdf.format(searchLoansOutputData.getLoanDetailList().get(i).getApprovedDate()));
}

String loanNumber = searchLoansOutputData.getLoanDetailList().get(i).getLoanNumber();
String firstName = searchLoansOutputData.getLoanDetailList().get(i).getFirstName();
String lastName = searchLoansOutputData.getLoanDetailList().get(i).getLastName();
String mobileNumber = searchLoansOutputData.getLoanDetailList().get(i).getMobileNumber();
String status = searchLoansOutputData.getLoanDetailList().get(i).getStatus().getDisplayName();
String loanAmount = String.valueOf(searchLoansOutputData.getLoanDetailList().get(i).getLoanAmount().setScale(0, BigDecimal.ROUND_UP));
String loanAppId = searchLoansOutputData.getLoanDetailList().get(i).getId();
BigDecimal productAmount = searchLoansOutputData.getLoanDetailList().get(i).getTotalProductAmount();
BigDecimal downPayment = searchLoansOutputData.getLoanDetailList().get(i).getDownPayment();
BigDecimal processingFee = searchLoansOutputData.getLoanDetailList().get(i).getProcessingFee();
String tenure = searchLoansOutputData.getLoanDetailList().get(i).getDesiredItemPaybackTenure();
String sourceAcquisition = searchLoansOutputData.getLoanDetailList().get(i).getSourceAcquisition();
List<SingleDocumentOuput> documentUpdatedList = searchLoansOutputData.getLoanDetailList().get(i).getDocOutputList();

dashboardStatusBean.setCreatedDate(createdDate);
dashboardStatusBean.setApproveDate(approveDate);
dashboardStatusBean.setLoanNumber(loanNumber);
dashboardStatusBean.setFirstName(firstName);
dashboardStatusBean.setLastName(lastName);
dashboardStatusBean.setMobileNumber(mobileNumber);
dashboardStatusBean.setStatus(status);
dashboardStatusBean.setLoanAppId(loanAppId);
dashboardStatusBean.setProductAmount(productAmount);
dashboardStatusBean.setDownPayment(downPayment);
dashboardStatusBean.setProcessingFee(processingFee);
dashboardStatusBean.setTenure(tenure);
dashboardStatusBean.setLoanAmount(loanAmount);
dashboardStatusBean.setDocumentUpdatedList(documentUpdatedList);

if (status.equals(LoanApplicationStatus.STILL_FILLING.getDisplayName()) ||
status.equals(LoanApplicationStatus.ONBOARDIN_IN_PROG.getDisplayName()) ||
status.equals(LoanApplicationStatus.INITIATED.getDisplayName()) ||
status.equals(LoanApplicationStatus.ADDITIONAL_DATA_REQ.getDisplayName()) ||
status.equals(LoanApplicationStatus.UPLOAD_IN_PROG.getDisplayName()) ||
status.equals(LoanApplicationStatus.VERIFIED.getDisplayName()) ||
status.equals(LoanApplicationStatus.LEAD.getDisplayName())) {
inProgressList.add(dashboardStatusBean);
}

Util.SALES_IN_PROGRESS_LIST = inProgressList;
}

} else {
displayMessage(searchLoansOutputData.getErrorCode(), searchLoansOutputData.getErrorMessage());
}
}
}

SalesLoginDashboardPresenter.java

    public class SalesLoginDashboardPresenter implements Presenter {

private SalesDashboardView mView;
private final SalesLoginInquiryUseCase mSalesInquiryUseCase;

@Inject
public SalesLoginDashboardPresenter(SalesLoginInquiryUseCase salesLoginInquiryUseCase) {
mSalesInquiryUseCase = salesLoginInquiryUseCase;
}

@Override
public void attachView(View v) {
mView = (SalesDashboardView) v;
}

public void handleSalesInquiryRequest(SearchLoansInput searchLoansInput) {
mView.displayLoadingScreen();
mSalesInquiryUseCase.setSalesLoginInquiryBody(searchLoansInput);
mSalesInquiryUseCase.execute()
.subscribe(this::onSalesInquiryReceived, this::onSalesInquiryError);
}

private void onSalesInquiryError(Throwable throwable) {
mView.hideLoadingScreen();
mView.displayErrorMessage("Error fetching data");
throwable.printStackTrace();
}

private void onSalesInquiryReceived(SearchLoansOutput searchLoansOutput) {
mView.hideLoadingScreen();
mView.handleSalesInquiryResponse(searchLoansOutput);
}
}

SalesLoginInquiryUseCase.java

    public class SalesLoginInquiryUseCase extends Usecase<SearchLoansOutput> {

private final MerchantRepository mRepository;
private final Scheduler mUiThread;
private final Scheduler mExecutorThread;
private SearchLoansInput mSearchLoansInput;
private String mCookie;

@Inject
public SalesLoginInquiryUseCase(
MerchantRepository repository,
@Named("ui_thread") Scheduler uiThread,
@Named("executor_thread") Scheduler executorThread) {

mRepository = repository;
mUiThread = uiThread;
mExecutorThread = executorThread;
}

public void setSalesLoginInquiryBody(SearchLoansInput searchLoansInput){
mSearchLoansInput = searchLoansInput;
}

@Override
public Observable<SearchLoansOutput> buildObservable() {
return mRepository.postSalesLoginDetailsInquiryBody(mSearchLoansInput)
.observeOn(mUiThread)
.subscribeOn(mExecutorThread);
}
}

最佳答案

我正在做一个关于在应用程序上无限滚动和学习 RxJava 的练习。

我在 StackOverflow 和其他网站上gandalfing,寻找好的示例和指南。

到目前为止我找到了this one ,我也在这里报告(当然,版权属于要点所有者)。

ApiService.class

public static Observable<List<String>> paginatedThings(final Observable<Void> onNextObservable) {
return Observable.create(new Observable.OnSubscribe<List<String>>() {
@Override
public void call(final Subscriber<? super List<String>> subscriber) {

onNextObservable.subscribe(new Observer<Void>() {
int latestPage = -1;
@Override
public void onCompleted() {
subscriber.onCompleted();
}

@Override
public void onError(Throwable e) {
subscriber.onError(e);
}

@Override
public void onNext(Void aVoid) {
latestPage++;
List<String> pageItems = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
pageItems.add("page " + latestPage + " item " + i);
}
subscriber.onNext(pageItems);
}
});
}
});
}

ReactiveList.java

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.rxandroid.api.RepresentativeApi;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.ButterKnife;
import butterknife.InjectView;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.subscriptions.CompositeSubscription;
import timber.log.Timber;

import static rx.android.app.AppObservable.bindActivity;

/**
* Created by Dustin on 2/14/15.
*/
public class ReactiveList extends Activity {

@InjectView(R.id.reactiveList)
RecyclerView reactiveList;

private ReactiveRecyclerAdapter adapter = new ReactiveRecyclerAdapter();
private LinearLayoutManager layoutManager;

private CompositeSubscription subscriptions = new CompositeSubscription();

private List<String> mockItems = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reactive_list);
ButterKnife.inject(this);

for (int i = 0; i < 100; i++) {
mockItems.add(String.valueOf(i));
}

reactiveList.setHasFixedSize(true);
reactiveList.setAdapter(adapter);
layoutManager = new LinearLayoutManager(this);
reactiveList.setLayoutManager(layoutManager);

adapter.addAll(mockItems);

Observable<Void> pageDetector = Observable.create(new Observable.OnSubscribe<Void>() {
@Override
public void call(final Subscriber<? super Void> subscriber) {
reactiveList.setOnScrollListener(new RecyclerView.OnScrollListener() {
int pastVisibleItems, visibleItemCount, totalItemCount;
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
visibleItemCount = layoutManager.getChildCount();
totalItemCount = layoutManager.getItemCount();
pastVisibleItems = layoutManager.findFirstVisibleItemPosition();

if ((visibleItemCount+pastVisibleItems) >= totalItemCount) {
subscriber.onNext(null);
}
}
});
}
}).debounce(400, TimeUnit.MILLISECONDS);

bindActivity(this, pageDetector);
Observable<List<String>> listItemObservable = RepresentativeApi.paginatedThings(pageDetector);
bindActivity(this, listItemObservable);
subscriptions.add(listItemObservable.observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<List<String>>() {
@Override
public void onCompleted() {
Timber.d("completed");
}

@Override
public void onError(Throwable e) {
Timber.e("error: " + e.getMessage());
}

@Override
public void onNext(List<String> strings) {
adapter.addAll(strings);
}
}));
}

public static class ReactiveRecyclerAdapter extends RecyclerView.Adapter<ReactiveRecyclerAdapter.ReactiveViewHolder> {

private List<String> items = new ArrayList<>();

public void addAll(List<String> moreItems) {
items.addAll(moreItems);
notifyDataSetChanged();
}

@Override
public ReactiveViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1,parent,false);
ReactiveViewHolder vh = new ReactiveViewHolder(v);
return vh;
}

@Override
public void onBindViewHolder(ReactiveViewHolder holder, int position) {
String item = items.get(position);
holder.label.setText(item);
}

@Override
public int getItemCount() {
return items.size();
}

public static class ReactiveViewHolder extends RecyclerView.ViewHolder {

TextView label;
public ReactiveViewHolder(View itemView) {
super(itemView);
label = (TextView) itemView.findViewById(android.R.id.text1);
}
}
}
}

如果您对其他工具感兴趣,请查看 Google Architecture .

目标是简化应用程序代码(为什么不呢,程序员的生活):你会发现 Paging library你可以用它来解决无尽的滚动(我目前也在研究这个)。顺便说一下,它使用 RxJava2

如果你愿意,这个GitHub repo上有一个例子这是用 Kotlin(!) 完成的。

结论:无限滚动可能非常棘手,我强烈建议您花时间学习和理解它的工作原理,无论是否使用库。

关于android - RecyclerView 使用 RxJava 无限滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50352358/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com