簡體   English   中英

將 Retrofit 與 RxJava 一起使用時,該應用程序會凍結一點

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

JSON

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

界面

public interface RetrofitInterface {

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

}

代碼

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) {
        
    }
});

我正在嘗試將 195 個國家/地區添加到ChipGroup但在添加芯片期間應用程序凍結了一點點,首先doOnSuccess方法中的代碼在onSuccess方法中,但應用程序凍結了一點點,所以代碼已移至doOnSuccess方法,但我收到此消息 只有創建視圖層次結構的原始線程才能觸及其視圖。

我是 RxJava 新手,有什么解決方案嗎?

您忘記在應該訂閱的內容上設置調度程序。 默認情況下,一個 Observable 和你應用到它的操作符鏈將在調用它的 Subscribe 方法的同一個線程上完成它的工作,並通知它的觀察者。 所以如果你從主線程調用它,它將在主線程上執行。 這就是您的應用程序凍結的原因,因為您在負責 UI 的主線程上發出網絡請求。

要修復它,只需使用 subscribeOn 方法設置另一個調度程序:

 .subscribeOn(Schedulers.io())

所以在你的情況下,它應該看起來像這樣:

getCountries().doOnSuccess(countryModels - > {
    ...
}).observeOn(AndroidSchedulers.mainThread())
  .subscribeOn(Schedulers.io())   // Asynchronously subscribes  to the observable on the IO scheduler.
  .subscribe(

    ...

)

詳細文檔: https://reactivex.io/documentation/operators/subscribeon.html

還有一篇有助於理解 RxJava 中的線程處理的文章: https://proandroiddev.com/understanding-rxjava-subscribeon-and-observeon-744b0c6a41ea

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM