Reputation: 2505
I'm accessing all of the views in a fragment with Kotlin Android Extensions, this views work as expected and can be accessed normally even after screen rotations.
The problem starts when i try to access the views inside an Rx-Java observable interval like this:
var interval = Observable.interval(10, TimeUnit.SECONDS, Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
interval.retry().subscribe { updateUi(); }
If i rotate the screen between intervals. The next time the updateUi() method is run as a part of the observable, the views inside it will be null and the application will crash with the following exception:
io.reactivex.exceptions.OnErrorNotImplementedException: text_view must not be null
But if i try to run the method outside the observable, everything will work correctly.
I know that accessing the views with findViewById() will retrieve the view correctly, but that defeats the purpuose of having the kotlin-android-extensions.
Upvotes: 1
Views: 581
Reputation: 7487
On rotation, the screen is being set up again, so the old views are gone.
You have to unsubscribe the subscription (returned by subscribe()
call) in the onStop()
.
Maybe you should try out ViewModel
of the Android architectures. I've been using it lately and really liking it. This will take care of your issue too. https://medium.com/google-developers/viewmodels-a-simple-example-ed5ac416317e
Upvotes: 4