Search code examples
androidkotlinpie-chartkotlin-coroutines

Kotlin Coroutines, pie chart doesn't spin


I have a problem with my pieChart spin function. When I call it in main threat it works exactly as expected but, when i call it in coroutines, it does nothing. I debugged the code,it goes into spinWheel() function but doesn't execute pieChart.spin function.

Here is the code.

  GlobalScope.launch {
         while (!isSpinned) {
             try {
                 rotationDegree = pieChart.rotationAngle - 270
                 if (rotationDegree > 40) {
                     isSpinned = true
                     pieChart.isRotationEnabled = false
                     pieChart.setTouchEnabled(false)
                     spinWheel(1800f + 270f + randNumber , 12000)
                     cancel()

                 }
                 delay(10)
             } catch (ex: Exception) {
                 Log.d("TAG", "onCreate: " + ex)
             }
         }
     }


 private fun spinWheel(spinDegree: Float, duration: Long) {

     pieChart.spin(duration.toInt(), 270f, spinDegree, Easing.EaseOutQuad)

 }

I used 'com.github.PhilJay:MPAndroidChart:v3.1.0' library for pie chart.

I get "android.util.AndroidRuntimeException: Animators may only be run on Looper threads" exception from catch. In this situation i really need to call this function after something happens so, how can i use this spin method ?


Solution

  • When I call the spin function in UIThread it worked correctly.

       runOnUiThread({
                pieChart.spin(duration.toInt(), startPoint, spinDegree, Easing.EaseOutQuad)
            })