0

After parsing the JSON data with the help of Volley library, I want to save it to Room. Since the process was taking too long (about 45 seconds) I put this inside a Service. In the same way, I was using AsyncTask to prevent the insert operation from freezing the interface. However, I decided to use RxJava because it is deprecated, but I did not understand most things. Can you help to create useful content?

Here are some questions;

  • In which case we should use Observable and in which case Single structure?
  • .observeOn(AndroidSchedulers.mainThread()) if we don't have work with mainThread, like in my example (running in service) then what should we do?
  • Do you really need it? I mean, we could handle this very easily with a really complicated AsyncTask.

Please share your knowledge (in Java please) make it a good article for readers

Thanks in advance


public class ScheduledService extends Service {
FoodDatabase appDatabase;
List<FoodArray> foodsArray;

 @Override
   public void onCreate() {
       super.onCreate();

       foodsArray = new ArrayList<>();

       appDatabase = Room.databaseBuilder(this, FoodDatabase.class, "FoodListDatabase_TEST.db")
               .fallbackToDestructiveMigration()
               .allowMainThreadQueries()
               .build();



       getFoodRequest();
}



   public void getFoodRequest() {
       Log.d("TAG_JSON_FOOD_DB", "--------------------------------");
       @SuppressLint("SetJavaScriptEnabled") JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
               Constant.FOOD_LIST_JSON, null,
               response -> {
                   long start = System.currentTimeMillis();
                   try {
                       JSONArray jsonArray = response.getJSONArray("MyData");
                       for (int i = 0; i < jsonArray.length(); i++) {
                           JSONObject object = jsonArray.getJSONObject(i);
                           FoodArray foodArray = new FoodArray();

                           List<FoodUnitsData> foodUnitList = new ArrayList<>();
                           FoodsData foodsData = new FoodsData();

                           foodsData.setFoodId(object.getString("food_id"));
                           foodsData.setFoodName(object.getString("food_name"));
                           foodsData.setFoodImage(object.getString("food_image"));
                           foodsData.setFoodUrl(object.getString("food_url"));
                           foodsData.setFoodKcal(object.getString("food_kcal"));
                           foodsData.setFoodDescription(object.getString("food_description"));
                           foodsData.setCarbPercent(object.getString("carb_percent"));
                           foodsData.setProteinPercent(object.getString("protein_percent"));
                           foodsData.setFatPercent(object.getString("fat_percent"));


                           JSONArray jsonUnitsArray = object.getJSONArray("units");

                           for (int k = 0; k < jsonUnitsArray.length(); k++) {
                               JSONObject unitobject = jsonUnitsArray.getJSONObject(k);

                               FoodUnitsData foodUnitData = new FoodUnitsData();
                               foodUnitData.setUnit(unitobject.getString("unit"));
                               foodUnitData.setAmount(unitobject.getString("amount"));
                               foodUnitData.setCalory(unitobject.getString("calory"));
                               foodUnitData.setCalcium(unitobject.getString("calcium"));
                               foodUnitData.setCarbohydrt(unitobject.getString("carbohydrt"));
                               foodUnitData.setCholestrl(unitobject.getString("cholestrl"));
                               foodUnitData.setFiberTd(unitobject.getString("fiber_td"));
                               foodUnitData.setIron(unitobject.getString("iron"));
                               foodUnitData.setLipidTot(unitobject.getString("lipid_tot"));
                               foodUnitData.setPotassium(unitobject.getString("potassium"));
                               foodUnitData.setProtein(unitobject.getString("protein"));
                               foodUnitData.setVitAIu(unitobject.getString("vit_a_iu"));
                               foodUnitData.setVitC(unitobject.getString("vit_c"));
                               foodUnitList.add(foodUnitData);
                           }
                           foodArray.setFoods(foodsData);
                           foodArray.setFoodUnits(foodUnitList);
                         foodsArray.add(foodArray);
                           //insertData(foodArray);

                       }
                   



                       insertData(foodsArray);

                       long finish = System.currentTimeMillis();
                       Log.d("TAG_JSON_FOOD_DB", "   \t" + (finish - start));
                       Log.d("TAG_JSON_FOOD_DB", "   \t" + "******************\n");
                   } catch (JSONException e) {
                       e.printStackTrace();
                       Log.d("TAG_JSON_FOOD", "e:" + e);
                   }
               }, error -> {
           Log.d("TAG_JSON_FOOD", error.toString());
       });
       jsonObjectRequest.setShouldCache(false);
       jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
       RequestQueue request_queue = Volley.newRequestQueue(context);
       request_queue.add(jsonObjectRequest);
   }



   private void insertData(List<FoodArray> foodArray) {
       Observable.fromCallable(() -> {
           for (int i = 0; i < foodArray.size(); i++) {
               appDatabase.daoAccess().insertAll(foodArray.get(i));
           }
           return appDatabase.daoAccess().getAll();
       })
               .subscribeOn(Schedulers.io())
               .observeOn(AndroidSchedulers.mainThread())
               .subscribe(new Observer< List<FoodArray>>() {
                   @Override
                   public void onSubscribe(@NonNull Disposable d) {
                       Log.d("TAG_JSON_FOOD_DB",  "***dis*****"+ d);
                   }

                   @Override
                   public void onNext(@NonNull  List<FoodArray> list) {
                       Log.d("TAG_JSON_FOOD_DB",  "***size*****"+ list.size());
                   }

                   @Override
                   public void onError(@NonNull Throwable e) {

                   }

                   @Override
                   public void onComplete() {
                       Log.d("TAG_JSON_FOOD_DB",  "***complete*****");
                   }
               });

   }


public void test(){
       Single.just(foodArray)
               .subscribeOn(Schedulers.io())
               .subscribe(new DisposableSingleObserver<Object>() {
                   @Override
                   public void onSuccess(Object obj) {
                       // work with the resulting todos...
                       dispose();
                   }

                   @Override
                   public void onError(Throwable e) {
                       // handle the error case...
                       dispose();
                   }});

}

}

Error


@Override
public void onComplete() {
    Log.d("TAG_JSON_FOOD_DB", "***complete*****");
     ///onDestroy();
}
  • you could very easily find answers to your questions by just doing some basic research on rxjava. if you can't integrate a piece of technology into your project, then first learn it and practice it more till you actually understand it – a_local_nobody Jan 25 '22 at 09:46
  • I invite you to share the information you have and the right approaches here. @a_local_nobody –  Jan 25 '22 at 10:02
  • [the right approach is to do research](https://stackoverflow.com/questions/42757924/what-is-the-difference-between-observable-completable-and-single-in-rxjava) – a_local_nobody Jan 25 '22 at 10:17
  • Sorry but there is not enough information. It needs to be explained with examples.. Apart from this, how we will use it in service, the value of observeOn needs to be explained as well. –  Jan 25 '22 at 10:33
  • I created this thread to learn. I'm sure it will be useful for everyone because there are not enough resources.. Please comment without insulting. –  Jan 25 '22 at 11:08

0 Answers0