【发布时间】:2021-12-30 14:52:58
【问题描述】:
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 新手,有什么解决方案吗?
【问题讨论】:
-
mmm 我不使用 Rx,但也许你可以使用新的 Handler(Looper.getMainLooper()) 并使用 post 方法来填充和显示芯片
标签: android retrofit retrofit2 rx-java rx-android