我想使用RxJava在RecyclerView上实现 Endless Scrolling 功能。
我想要的是什么:我想从API调用中获取前10个数据并将其显示在RecyclerView中。用户向下滚动这10个数据后,我想进行另一个API调用并拉出另外10个数据。再次当用户在这些最新的10个数据之后向下滚动时,我必须为另外10个数据进行API调用。这将持续到API调用提供所有数据。
我尝试使用取运算符但未获得所需的结果。我搜索了不同的运算符,但没有获得单个运算符或任何运算符组合来实现此目的。任何帮助将不胜感激。
我的代码如下所示。
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);
}
}
答案 0 :(得分:3)
我正在做一个关于应用程序无休止滚动和学习 RxJava 的练习。
我在StackOverflow和其他网站周围 gandalfing ,寻找好的样本和指南。
到目前为止,我找到了Way to find an image inside another image in PHP/GD?,我也在这里报告(当然,版权归给主人所有)。
<强> 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);
}
}
}
}
如果您对其他工具感兴趣,请查看this one。
目标是简化应用程序代码(为什么不是,编码器生活):你会找到Google Architecture,你可以使用它来解决无尽的滚动(我目前正在研究它)。顺便说一句,它使用 RxJava2 。
如果你愿意,这个Paging library就有一个例子,它是用Kotlin(!)完成的。
结论:无限滚动可能非常棘手,我强烈建议您花时间学习和理解它是如何工作的,无论是否使用图书馆。
答案 1 :(得分:2)
您可以尝试Android paging library。另外,请阅读this以了解如何实施它。
答案 2 :(得分:-1)
你能做的是:
获取可为您的回收器适配器发送连续数据的观察
使用debounce / window / buffer之一传递从可观察源发出数据的时间跨度
观察发射 - 您可以通知适配器并自动添加数据
通过这种方式,您可以获得无限滚动,并且不需要时间来加载数据(因为您只获取了在特定时间内发出的数据)
fun getData():Observable<String>{
return Observable.just(your source).debounce(time,unit)
}
//where you observe getData().subscribe({here you get the string that emitted
//within your given time you can add into your list and pass
//this to adapter and notify it})
getData().subscribe({
listOfString.addAll(it)
rvadapter.setlist(listOfString)
rvadapater.notifydatasetchanage()
})
你也可以使用flowable;为此,你必须通过背压策略。