Observable OnCompleted无法更新UI

时间:2015-04-05 18:12:04

标签: java android observable rx-java

我正在尝试Toast完成服务电话。但是在onComplete方法中,我收到了这个例外:

  

java.lang.RuntimeException:无法在未调用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 StackOverflow
            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操作?

3 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:5)

最初:

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

此更改后,它正在运行:

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

答案 2 :(得分:1)

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

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