What I want to achieve: I am loading data from some web service in recyclerView. I want to load first 10 data and display it in recyclerView. When User scrolls, call web service for another 10 data to display it.
What I have done: For above aim, I'm using .take operator of RxJava. But It seems not working for me or else I'm doing some mistake.
What issue I'm having: I'm getting all the data instead of first 5 data. There might be something that I'm missing it.
My code is like below.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private final String TAG = MainActivity.class.getSimpleName();
private RecyclerView recyclerView;
private ProgressDialog mProgressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
setupProgressDialog();
ApiEndPoints apiEndPoints = ApiClient.getClient().create(ApiEndPoints.class);
mProgressDialog.show();
apiEndPoints.fetchAllUsers()
.take(5)
.subscribeOn(Schedulers.io()) //Background Thread
.observeOn(AndroidSchedulers.mainThread()) //UI Thread
.subscribe(new Observer<List<Pojo>>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(List<Pojo> pojoList) {
recyclerView.setAdapter(new RVAdapter(pojoList));
Log.e(TAG, "List Size: " + pojoList.size());
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
mProgressDialog.dismiss();
}
}
);
}
private void setupProgressDialog() {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Loading . . . ");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
}
}
Ask me if anything required. Thanks in advance.
答案 0 :(得分:0)
如果使用Take运算符,它将发出前5个项目,然后onCompleted函数将触发。因此,您需要可观察的来源。
我在github上找到了示例应用程序,该应用程序使用rxjava进行更多操作。
答案 1 :(得分:0)
您会收到一个列表,该列表被视为对象。您需要对其进行迭代,先获取5个,然后再将其作为列表返回:
apiEndPoints.fetchAllUsers()
// iterate users
.concatMap(new Func1<List<Pojo>, Observable<Pojo>>() {
@Override
public Observable<Pojo> call(List<Pojo> pojos) {
return Observable.from(pojos);
}
})
// take 5 from iteration
.take(5)
// put all 5 users back to a list
.toList()
.subscribeOn(Schedulers.io()) //Background Thread
.observeOn(AndroidSchedulers.mainThread()) //UI Thread
如果您有一个数组(Pojos[] users
)take()
运算符应该没有迭代地工作。