首页 > 解决方案 > 在 Rx 回调中取消了已关闭的变量

问题描述

我的理解是,在下面的代码中,变量context永远不应该为空。

但是,当附加调试器时,执行 lambda 时变量上下文通常为空。

这种行为可重现五次之三。

这怎么解释?

object MyOtherService {
  private val TAG = "MyOtherService"

  fun start(context:Context){
    context.getString(android.R.string.ok) // no exception

    Log.d(TAG, "context ok")

    SlowServiceObserver
      .getObservable()
      .observeOn(Schedulers.computation())
      .subscribe({
        context.getString(android.R.string.ok) // null reference exception thrown sometimes
      })
  }
}

public class MyApp extends Application {

  public void onCreate(){
    super.onCreate();

    MyService.INSTANCE.start(this);

    SlowService slowService = new SlowService();
    SlowServiceObserver.INSTANCE.notify(slowService);
  }    
}

object SlowServiceObserver {

  private val mBehaviorSubject : BehaviorSubject<BehaviorSubject> = BehaviorSubject.create()

  fun getObservable(){
    return mBehaviorSubject
  }

  fun notify(instance: SlowService){
     mBehaviorSubject.onNext(instance)
  }
}

会不会是 Kotlinobject以某种方式改变了闭包?或者这是 RxJava 中的一些预期行为?

编辑

尝试的解决方法:

堆栈跟踪

art/runtime/runtime.cc:286] Pending exception java.lang.NullPointerException thrown by 'void MyOtherService.start(android.content.Context):39'
art/runtime/runtime.cc:286] java.lang.NullPointerException: Attempt to read from field 'java.lang.String MyOtherService.TAG' on a null object reference
art/runtime/runtime.cc:286]   at void MyOtherService.start(android.content.Context) (MyOtherService.kt:39)
art/runtime/runtime.cc:286]   at void MyApplication.onCreate() (MyApplication.java:106)
art/runtime/runtime.cc:286]   at void android.app.Instrumentation.callApplicationOnCreate(android.app.Application) (Instrumentation.java:1026)

akarnokd 提出这是(kotlin?)编译器中的一个错误。或者它可能是 Android Studio 中的一个错误?

编辑 2

根据评论,我尝试制作包含样本并检查了另一个工作副本。context无论我尝试重现该问题多少次,它都不为空。我想这个问题一定与一些中间构建工件有关。清理/重建项目和无效缓存并没有帮助。

标签: androidkotlinrx-java2

解决方案


推荐阅读