@@ -11,8 +11,12 @@ import android.graphics.Paint
1111import android.graphics.RectF
1212import android.util.AttributeSet
1313import android.view.View
14+ import kotlinx.coroutines.experimental.CoroutineScope
15+ import kotlinx.coroutines.experimental.Dispatchers
1416import kotlinx.coroutines.experimental.Job
15- import kotlinx.coroutines.experimental.android.UI
17+ import kotlinx.coroutines.experimental.android.Main
18+ import kotlinx.coroutines.experimental.android.awaitFrame
19+ import kotlinx.coroutines.experimental.cancelChildren
1620import kotlinx.coroutines.experimental.launch
1721import java.util.*
1822
@@ -58,9 +62,11 @@ class AnimationView(
5862
5963private val rnd = Random ()
6064
61- class AnimationModel : ViewModel () {
65+ class AnimationModel : ViewModel (), CoroutineScope {
66+
67+ override val coroutineContext = Job () + Dispatchers .Main
68+
6269 private val shapes = MutableLiveData <Set <AnimatedShape >>()
63- private val jobs = arrayListOf<Job >()
6470
6571 fun observe (owner : LifecycleOwner , observer : Observer <Set <AnimatedShape >>) =
6672 shapes.observe(owner, observer)
@@ -71,13 +77,13 @@ class AnimationModel : ViewModel() {
7177 }
7278
7379 fun addAnimation () {
74- jobs + = launch( UI ) {
80+ launch {
7581 animateShape(if (rnd.nextBoolean()) AnimatedCircle () else AnimatedSquare ())
7682 }
7783 }
7884
7985 fun clearAnimations () {
80- jobs.forEach { it.cancel() }
86+ coroutineContext.cancelChildren()
8187 shapes.value = NO_SHAPES
8288 }
8389}
@@ -101,7 +107,7 @@ suspend fun AnimationModel.animateShape(shape: AnimatedShape) {
101107 var time = System .nanoTime() // nanos
102108 var checkTime = time
103109 while (true ) {
104- val dt = time.let { old -> UI . awaitFrame().also { time = it } - old }
110+ val dt = time.let { old -> awaitFrame().also { time = it } - old }
105111 if (dt > 0 .5e9) continue // don't animate through over a half second lapses
106112 val dx = shape.x - 0.5f
107113 val dy = shape.y - 0.5f
@@ -121,7 +127,7 @@ suspend fun AnimationModel.animateShape(shape: AnimatedShape) {
121127 when (rnd.nextInt(20 )) { // roll d20
122128 0 -> {
123129 animateColor(shape) // wait a second & animate color
124- time = UI . awaitFrame() // and sync with next frame
130+ time = awaitFrame() // and sync with next frame
125131 }
126132 1 -> { // random speed change
127133 sx = rnd.nextSpeed()
@@ -138,7 +144,7 @@ suspend fun AnimationModel.animateColor(shape: AnimatedShape) {
138144 val aColor = shape.color
139145 val bColor = rnd.nextColor()
140146 while (true ) {
141- val time = UI . awaitFrame()
147+ val time = awaitFrame()
142148 val b = (time - startTime) / duration
143149 if (b >= 1.0f ) break
144150 val a = 1 - b
0 commit comments