从RxAndroid访问项目布局()

人生难得几回搏,此时不搏待何时。这篇文章主要讲述从RxAndroid访问项目布局?相关的知识,希望能为你提供帮助。
我使用下面的代码:

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();

答案原因是你正在努力展示进展 - >
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()方法返回的字符串。
另一答案【从RxAndroid访问项目布局()】你必须订阅主线程:
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(); } }));


    推荐阅读