Android 在Flowable中收集2个并行发布服务器的结果
我对反应式编程非常陌生,但我尝试将rxjava应用于收集通话和短信列表,并将其合并为一个列表。其思想是以并行方式迭代游标,并发出顺序项。 在此之后,所有项目都被收集到一个列表中 但在doOnComplete中,并不是所有的数据都收集到了,我有大约150个项目,而且只添加了约25个。 我认为问题在于Flowable.concat不会等待所有项目,但这只是一个建议Android 在Flowable中收集2个并行发布服务器的结果,android,rx-java,reactive-programming,rx-android,Android,Rx Java,Reactive Programming,Rx Android,我对反应式编程非常陌生,但我尝试将rxjava应用于收集通话和短信列表,并将其合并为一个列表。其思想是以并行方式迭代游标,并发出顺序项。 在此之后,所有项目都被收集到一个列表中 但在doOnComplete中,并不是所有的数据都收集到了,我有大约150个项目,而且只添加了约25个。 我认为问题在于Flowable.concat不会等待所有项目,但这只是一个建议 public void readLatestActivity() { Cursor callsCursor = getCalls
public void readLatestActivity() {
Cursor callsCursor = getCallsCursor();
Cursor smsCursor = getSmsCursor();
if (callsCursor == null || smsCursor == null) {
return;
}
SortedSet<MActivity> activities = new TreeSet<>((left, right) -> left.getReceiveTime() < right.getReceiveTime() ? 1 : 0);
Flowable.concat(getCallsPublisher(callsCursor), getSmsPublisher(smsCursor))
.subscribeOn(Schedulers.io())
.doOnNext(new Consumer<MActivity>() {
@Override
public void accept(@NonNull MActivity mActivity) throws Exception {
if (mActivity != null){
activities.add(mActivity);
}
}
})
.observeOn(AndroidSchedulers.mainThread())
.doOnComplete(new Action() {
@Override
public void run() throws Exception {
Timber.d("doOnComplete");
callsCursor.close();
smsCursor.close();
mBus.post(new EActivities(activities)); //<--- here I'm getting ~25 items
}
})
.subscribe();
}
private Publisher<MActivity> getCallsPublisher(Cursor callsCursor) {
return Flowable.fromIterable(RxCursorIterable.from(callsCursor))
.take(callsCursor.getCount() < LIMIT ? callsCursor.getCount() : LIMIT)
.subscribeOn(Schedulers.computation())
.parallel()
.runOn(Schedulers.computation())
.map((Function<Cursor, MActivity>) this::readCallFromCursor)
.sequential()
.observeOn(AndroidSchedulers.mainThread());
}
private Publisher<MActivity> getSmsPublisher(Cursor smsCursor) {
return Flowable.fromIterable(RxCursorIterable.from(smsCursor))
.take(smsCursor.getCount() < LIMIT ? smsCursor.getCount() : LIMIT)
.subscribeOn(Schedulers.computation())
.parallel()
.runOn(Schedulers.computation())
.map((Function<Cursor, MActivity>) this::readSmsFromCursor)
.sequential()
.observeOn(AndroidSchedulers.mainThread());
}
我认为问题在于创建树集时使用的比较器。当left.getReceiveTime>right.getReceiveTime时,它不会返回-1,即某些活动被错误地认为是重复的 我还建议简化getCallsPublisher代码,如下所示:
return Flowable.generate(getCallsCursor(),
(cursor, emitter) -> {
if (!cursor.isClosed() && cursor.moveToNext())
emitter.onNext(readCallFromCursor(cursor));
else
emitter.onComplete();
}, Cursor::close)
.take(LIMIT);
以及摆脱RxCursorIterable。谢谢你的回答。请您在不使用lambda的情况下编写此代码段,因为我想了解您正在使用哪些函数。@AnZ我正在使用此函数:generateinitialState、generator、disposeState
return Flowable.generate(getCallsCursor(),
(cursor, emitter) -> {
if (!cursor.isClosed() && cursor.moveToNext())
emitter.onNext(readCallFromCursor(cursor));
else
emitter.onComplete();
}, Cursor::close)
.take(LIMIT);