Hello everyone I am stuck on a kotlin coroutine. Appreciate if someone can help me on that.
I am launching a coroutine that after a specified delay display a counter value on the screen.
job = launch(UI) {
var count= 0
while (true) {
textView.text = "${count++}"
delay(200L)
}
}
}
Now on screen rotation I want UI keeps getting updated with correct counter value. Does someone has any idea how to resume the job on configuration(e.g. screen rotation) change?
t
thevery
09/15/2018, 9:31 PM
Easy hack - replace textview with getter. Proper way - stop/start or attach/detach on pause/resume
p
Paul Woitaschek
09/15/2018, 11:05 PM
Make the count variable a property of your activity and save it in onSaveInstanceState
k
Kotlin
09/16/2018, 1:30 AM
@Paul Woitaschek@thevery Thanks. I got misdirected. Actually I was thinking how to make coroutine's job itself save the counter value rather than doing it ourself like saving inside onSaveInstanceState(). I was expecting some sort of magic from coroutine ☹️ Now I am good. Thanks.
s
Sam
09/16/2018, 2:25 AM
Use ViewModels to avoid boiler plate
➕ 4
g
gildor
09/16/2018, 3:42 AM
I hardly can imagine such magic, only move out this coroutine from activity (to ViewModel or Application, depends on your case), coroutine is just an object and follows all object rules, you can in theory setialize coroutine state (now it's not easy, but possible), but even in this case you should save serialized data somewhere during activity orientation change
u
uli
09/16/2018, 8:51 AM
Coroutines can actually be serialized. I remember seeing something like that here in slack. I think it was part of a Bluetooth framework.
In your case a serialized coroutine would probably keep updating a text view that has already been destroyed
g
gildor
09/16/2018, 10:17 AM
Yes, sure, they can, but now it requires some additional boilerplate and explicit context restoring, there is some work to make it easier