0

to iterate through array list one can use following code

 List<LatLng> latLngs = new ArrayList<>();
                        latLngs.add(new LatLng(5,5));

                        Observable.just(latLngs)
                                .concatMap(array -> Observable.fromIterable(array))
                                .subscribe(v-> Log.d(TAG, "subscribeToTopic: "+v.latitude));

but how to iterate through JSONarray like this using Rxjava?

 [{
    "vehicleId": "5c11e863a361762fdbe99fae",
    "latitude": "19.952829",
    "latitudeDir": "N",
    "longitude": "73.735054",
    "longitudeDir": "E",
    "speed": "0.0",
    "ignition": "0",
    "batteryStatus": "1"
 }, {
    "vehicleId": "5c11e863a361762fdbe99fae",
    "latitude": "19.952829",
    "latitudeDir": "N",
    "longitude": "73.735054",
    "longitudeDir": "E",
    "speed": "0.0",
    "ignition": "0",
    "batteryStatus": "1"
 }, {
    "vehicleId": "5c11e863a361762fdbe99fae",
    "latitude": "19.952829",
    "latitudeDir": "N",
    "longitude": "73.735054",
    "longitudeDir": "E",
    "speed": "0.0",
    "ignition": "0",
    "batteryStatus": "1"
 }, {
    "vehicleId": "5c11e863a361762fdbe99fae",
    "latitude": "19.952829",
    "latitudeDir": "N",
    "longitude": "73.735054",
    "longitudeDir": "E",
    "speed": "0.0",
    "ignition": "0",
    "batteryStatus": "1"
 }]
1
  • why are you iterating a collection with Rx when you could in this case just use a regular for loop Commented Dec 19, 2018 at 9:33

1 Answer 1

2

Since JSONArray implements the List interface (assuming that you using simplejson here), you can pretty much do the same:

JSONArray jsonArray = new JSONArray();
Observable.fromIterable(jsonArray)
  .subscribe(e -> {
    System.out.println((JSONObject) e);
  });

EDIT: based on your comments i think you're not using simplejson but this org.json.JSONArray which does not implement the List interface. In this case you can iterate like this:

JSONArray jsonArray = new JSONArray();
Observable.range(0,jsonArray.length())
  .map(jsonArray::get)
  .subscribe(e -> {
     System.out.println((JSONObject) e);
  });
Sign up to request clarification or add additional context in comments.

2 Comments

gives error... i have already tried this. fromIterable (java.lang.Iterable<? extends T>) in Observable cannot be applied to (org.json.JSONArray)
i also tried right now, it seems to work for me. Can you share some additional info, what versions are you using from rx and from simplejson. and what is the exact error message?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.