我有以下场景,我需要在RxJava中对其进行转换:
到目前为止,我所做的事情是这样的:
fetchAllFromDbObservable()
.flatMap( (string) -> {
return Model
})
.buffer(30)
.publish( (List<Model>, Response) -> {
return callApiObservable(List<Model>);
})
.publish( (Response) -> {
// how do I get access here to List<Model> ?
ArrayList<Long> ids = getIdsFromList(List<Model>)
return removeFromDbObservable(ids);
})
问题:
由于
答案 0 :(得分:0)
您的要求的可能实施可能如下:
import rx.subjects.PublishSubject;
import java.util.List;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.toList;
public class Looper {
// initialize db with 100 items
private final List<Integer> db = IntStream.rangeClosed(1, 100)
.boxed().collect(toList());
private List<Integer> read30ItemsFromDb() {
return db.stream().limit(30).collect(toList());
}
private void makeApiCall(List<Integer> items) {
System.out.println(items);
}
private void removeFromDb(List<Integer> itemsToBeRemoved) {
db.removeAll(itemsToBeRemoved);
}
private enum Command { NEXT }
public static void main(String[] args) {
Looper looper = new Looper();
PublishSubject<Command> itemsProducer = PublishSubject.create();
PublishSubject<List<Integer>> itemsConsumer = PublishSubject.create();
itemsProducer.subscribe(command -> {
switch (command) {
case NEXT:
List<Integer> items = looper.read30ItemsFromDb();
if (!items.isEmpty()) itemsConsumer.onNext(items);
else itemsConsumer.onCompleted();
default:
itemsConsumer.onCompleted();
}
});
itemsConsumer
.doOnCompleted(itemsProducer::onCompleted)
.subscribe(items -> {
looper.makeApiCall(items);
looper.removeFromDb(items);
itemsProducer.onNext(Command.NEXT);
});
// start the loop
itemsProducer.onNext(Command.NEXT);
}
}