In my Android client I receive this JSON data from a backend:
[
[
1427378400000,
553
],
[
1427382000000,
553
]
]
List<ProductLevel> productLevels = new ArrayList<>();
for(List<Double> p: list) {
productLevels.add(new ProductLevel(p.get(0),p.get(1)));
}
I think it should work.
If you change readProductLevels
to emit each list item one at a time, you can
then react to them one at a time:
In mProductService:
private Observable<List<Double>> readProductLevels() {
return Observable.create(
new Observable.OnSubscribe<List<Double>>() {
@Override
public void call(Subscriber<? super List<Double>> subscriber) {
List<List<Double>> items = new ArrayList<List<Double>>();
List<Double> list1 = new ArrayList<Double>() {{
add(1D);
add(2D);
}};
items.add(list1);
List<Double> list2 = new ArrayList<Double>() {{
add(10D);
add(12D);
}};
items.add(list2);
List<Double> list3 = new ArrayList<Double>() {{
add(21D);
add(22D);
}};
items.add(list3);
// Imagine the list creation above is your Json parsing
for (List<Double> list : items) {
subscriber.onNext(list);
}
subscriber.onCompleted();
}
});
}
Allows you to subscribe to each item in your super list:
private void getProductLevels() {
Observable<List<Double>> responseObservable = readProductLevels();
AppObservable.bindFragment(this, responseObservable)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
// TODO: Transform List<List<Double>> into List<ProductLevel>
.subscribe(
new Subscriber<List<Double>>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(List<Double> response) {
new ProductLevel(response.get(0), response.get(1));
}
});
}
According to your Data, you receive a list of pair (timestamp, level). This pair is represented by a list which contains only 2 values.
So you want to emit each pair, and transform each pair into a ProductLevel
.
To do this, you'll have to flatMap
your list of pair to emit each pair. Then to map
each pair into a ProductLevel
. Finally, just build a list
with all emited items.
(java8 style)
AppObservable.bindFragment(this, responseObservable)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.flatMapIterable(listOfList -> listOfList) // or flatMap(l -> Observable.from(l))
.map(pair -> new ProductLevel(pair.get(0),pair.get(1))) // build ProductLevel for each pair
.toList() // build a list with all ProductLevel
.subscribe(listOfProductLevel -> /** ... **/);