Hello everyone I am stuck on a kotlin coroutine. A...
# coroutines
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?
Easy hack - replace textview with getter. Proper way - stop/start or attach/detach on pause/resume
Make the count variable a property of your activity and save it in onSaveInstanceState
@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.
Use ViewModels to avoid boiler plate
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
Yes, sure, they can, but now it requires some additional boilerplate and explicit context restoring, there is some work to make it easier