我正在使用以下代码:
mCompositeDisposable.add(myObservable(IdLang, shortTermCoursesModels)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableObserver<String>() {
@Override
public void onComplete() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String string) {
listenerCoursesListItemService.adapterHideProgress();
}
}));
和
private Observable<String> myObservable(String IdLang, List<GetShortTermCoursesModel> shortTermCoursesModels) {
return Observable.defer(new Callable<ObservableSource<? extends String>>() {
@Override
public ObservableSource<? extends String> call() throws Exception {
listenerCoursesListItemService.adapterShowProgress();
for (int i = 0; i < 900000; i++) {
Log.i("WWWWWWWW", "A " + i);
}
return Observable.just("ok");
}
});
但是请告诉我以下错误:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
如何从UI
访问RxAndroid
。
我的错误在这里:
listenerCoursesListItemService.adapterShowProgress();
listenerCoursesListItemService.adapterHideProgress();
答案 0 :(得分:0)
你必须订阅主线程:
mCompositeDisposable.add(myObservable(IdLang, shortTermCoursesModels)
.subscribeOn(AndroidSchedulers.mainThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableObserver<String>() {
@Override
public void onComplete() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String string) {
listenerCoursesListItemService.adapterHideProgress();
}
}));
答案 1 :(得分:0)
原因是您正在尝试显示进度 - &gt;
listenerCoursesListItemService.adapterShowProgress();
内部的call()方法,它实际上运行在不同的线程(Schedulers.io())而不是UI线程(AndroidSchedulers.mainThread())。
相反,您可以在doOnSubscribe()方法中显示进度,并在onComplete()中将其关闭。两种方法都将在UI线程上调用。更新了以下代码以供参考,
mCompositeDisposable.add(myObservable(IdLang, shortTermCoursesModels)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(new Consumer<Disposable>() {
@Override
public void accept(@NonNull Disposable disposable) throws Exception {
listenerCoursesListItemService.adapterShowProgress();
}
})
.doFinally(new Action() {
@Override
public void run() throws Exception {
listenerCoursesListItemService.adapterHideProgress();
}
})
.subscribeWith(new DisposableObserver<String>() {
@Override
public void onComplete() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String string) {
}
}));
和
private Observable<String> myObservable(String IdLang, List<GetShortTermCoursesModel> shortTermCoursesModels) {
return Observable.defer(new Callable<ObservableSource<? extends String>>() {
@Override
public ObservableSource<? extends String> call() throws Exception {
for (int i = 0; i < 900000000; i++) {
Log.i("WWWWWWWW", "A " + i);
}
return Observable.just("ok");
}
});
}
在onNext()内部,您将获得从call()方法返回的字符串。