Saturday, 1 January 2022

The app is freezing for a little bit when using Retrofit with RxJava

JSON

[
   {
      "countryName":"..."
   },
   {
      "countryName":"..."
   },
   {
      "countryName":"..."
   } //etc... to 195 countries
]

Interface

public interface RetrofitInterface {

    @GET("GetCountries.php")
    Single<List<CountryModel>> getCountries();

}

Code

new Retrofit.Builder().baseUrl(Constants.BASE_URL).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJava3CallAdapterFactory.create()).build().create(RetrofitInterface.class).getCountries().doOnSuccess(countryModels - > {
    for (CountryModel item: countryModels) {
        Chip chip = new Chip(requireContext());
        chip.setText(item.getCountryName());
        fragmentCountriesBinding.fragmentCountriesChipGroupMain.addView(chip);
    }
}).observeOn(AndroidSchedulers.mainThread()).subscribe(new SingleObserver < List < CountryModel >> () {
    @Override
    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {
        
    }

    @Override
    public void onSuccess(@io.reactivex.rxjava3.annotations.NonNull List < CountryModel > countryModels) {
        
    }

    @Override
    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
        
    }
});

I'm trying to add 195 countries to the ChipGroup but the app is freezing for a little bit during adding the chips, Firstly the code inside the doOnSuccess method was in the onSuccess method but the app was freezing for a little bit, So the code has been moved to doOnSuccess method but I get this message Only the original thread that created a view hierarchy can touch its views.

I'm new with RxJava, Any solutions?



from The app is freezing for a little bit when using Retrofit with RxJava

No comments:

Post a Comment