Observable OnCompleted 无法更新 UI

Observable OnCompleted cannot update UI

我正在尝试 Toast 完成服务呼叫。但是在 onComplete 方法中我收到这个异常:

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

它是从 SafeSubscriber#onNext(T args) 抛出的,看起来像这样:

/**
     * Provides the Subscriber with a new item to observe.
     * <p>
     * The {@code Observable} may call this method 0 or more times.
     * <p>
     * The {@code Observable} will not call this method again after it calls either {@link #onCompleted} or
     * {@link #onError}.
     * 
     * @param args
     *          the item emitted by the Observable
     */
    @Override
    public void onNext(T args) {
        try {
            if (!done) {
                actual.onNext(args);
            }
        } catch (Throwable e) {
            // we handle here instead of another method so we don't add stacks to the frame
            // which can prevent it from being able to handle Whosebug
            Exceptions.throwIfFatal(e);
            // handle errors if the onNext implementation fails, not just if the Observable fails
            onError(e);
        }
    }

这是我的代码中出现问题的代码片段:

 NetworkService.aService()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread()) 
                    .flatmap(anotherCall)
                    .subscribe(new Subscriber<AddCommentResponse>() {
                @Override
                public void onCompleted() {
                    Toast.makeText(...).show();
                    navigateBack();
                }

                // etc. ...

问题是我无法从 onCompleted 方法更新 UI 吗?或者我应该在哪里处理 UI 操作?

NetworkService 在工作线程上。您正在从工作线程调用 makeText(..) ,它应该从 UI 线程调用。尝试创建一个 Handler 并在其中烘烤。

ActivityContext.runOnUiThread(new Runnable() { 
  public void run() { 
Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();
  } 
}); 

也许 anotherCall 在另一个线程上观察。在 flatMap 调用之后移动 observeOn(在 android 主线程上)。

原来:

NetworkService.aService()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread()) 
                    .flatmap(anotherCall)

此更改后它正在运行:

NetworkService.aService()
                    .flatmap(anotherCall)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())