android - 在 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 中的一些预期行为?
编辑
尝试的解决方法:
- 引入带有上下文的私有属性并在订阅回调中使用它 - 有效 - 没有例外
- 将一次性物品分配给私人财产 - 无济于事
- 将 kotlin 对象更改为类并从应用程序调用 - 新异常(仅附加调试器):
堆栈跟踪
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
无论我尝试重现该问题多少次,它都不为空。我想这个问题一定与一些中间构建工件有关。清理/重建项目和无效缓存并没有帮助。
解决方案
推荐阅读
- webhooks - 松弛的 webhook 可以在单个 webhook 请求中提及多个用户吗?
- haskell - Haskell 动态程序效率
- c - PC Lint 标头错误解析,错误 129:预期声明,标识符“T_TEST_ID”被忽略
- javascript - 添加输入参数时moveBall函数不起作用
- apache - .htaccess 安全标头未出现在请求中
- html - Swift 中 PDFKit 的 HTML 分页后差距很大
- javascript - 使用 Vue 异步 Axios 数据
- gmail - nodemailer OAuth2 gsuite (mail@example.com) serviceClient 和 privateKey 配置
- rust - 嵌套迭代器上 self 的生命周期问题“返回此值需要为 `'a 借用 `*self`”
- javascript - 在 jQuery 中使用循环创建的无线电输入都被分配了相同的值