我正在尝试将CombineLatest与多个RxTextViews一起使用,我认为我已经正确处理了Disposables,但看起来仍然出现内存泄漏。
val one = RxTextView.afterTextChangeEvents(one)
val two = RxTextView.afterTextChangeEvents(two)
val three = RxTextView.afterTextChangeEvents(three)
val four = RxTextView.afterTextChangeEvents(four)
val five = RxTextView.afterTextChangeEvents(five)
val disposable = Observables.combineLatest(one, two, three, four, five) { oneEvent, twoEvent, threeEvent, fourEvent, fiveEvent ->
//combining happening with these strings: oneEvent.view().text.toString }
.skip(1)
.debounce(1000, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
//network call
}
compositeDisposable.add(disposable)
}
然后在我的onStop
中处理它。
override fun onStop() {
super.onStop()
if (!compositeDisposable.isDisposed) {
compositeDisposable.dispose()
}
}
我了解到,如果在onNext()方法中引用了某些视图,则可能会发生NullPointerException,这是我认为正在发生的情况。这是我得到的NPE:
fatal Exception: java.lang.NullPointerException: view == null
at com.jakewharton.rxbinding2.internal.Preconditions.checkNotNull(Preconditions.java:27)
at com.jakewharton.rxbinding2.widget.RxTextView.afterTextChangeEvents(RxTextView.java:159)
at MyFragment$setUpTextListeners$1.execute(MyFragment.kt:170)
这是我正在使用的片段:
private lateinit var viewModel: MyViewModel
private lateinit var binding: FragmentMyThingsBinding
private val compositeDisposable = CompositeDisposable()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentMyThingsBinding.inflate(inflater, container, false)
viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
binding.viewModel = viewModel
//calls to kick off business logic
return binding.root
}
override fun onStart() {
super.onStart()
setUpTextListeners()
}
override fun onStop() {
super.onStop()
if (!compositeDisposable.isDisposed) {
compositeDisposable.dispose()
}
}
private fun setUpTextListeners() {
val one = RxTextView.afterTextChangeEvents(one)
val two = RxTextView.afterTextChangeEvents(two)
val three = RxTextView.afterTextChangeEvents(three)
val four = RxTextView.afterTextChangeEvents(four)
val five = RxTextView.afterTextChangeEvents(five)
compositeDisposable.add(Observables.combineLatest(one, two, three, four, five) { oneEvent, twoEvent, threeEvent, fourEvent, fiveEvent ->
//combine here using oneEvent.view().text.toString }
.skip(1)
.debounce(1000, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
//network call
})
}
}
答案 0 :(得分:1)
您传递给RxTextView.afterTextChangeEvents
的视图之一为空。有assert in that function,它检查null
上的传入参数。
那个问题与内存泄漏无关。
编辑:
将合成视图属性更改为使用binding.editText
可解决此问题。 (讨论评论)