6

Is it possible to know all the status of a coroutine Job ?

I find this function extension but I can't access to all the status of a Job :

fun Job.status(): String = when {
    isCancelled -> "cancelled"
    isActive -> "Active"
    isCompleted -> "Complete"
    else -> "Nothing"
}

There is no isNew, isCancelling or isWaitingForChildren functions with the Job classe. Why ?

enter image description here

Jéwôm'
  • 3,753
  • 5
  • 40
  • 73
  • 3
    https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/ – IR42 Feb 11 '20 at 15:04
  • I wonder why would you need it? For debugging you can just print `job.toString()`. If you have some real use-case to get the status, then can you please explain it in a separate issue at https://github.com/Kotlin/kotlinx.coroutines – Roman Elizarov Feb 12 '20 at 10:08
  • It's just for a better understanding of the Job cyclelife. Just learning. – Jéwôm' Feb 12 '20 at 12:14

1 Answers1

7

Thanks to Drawn Roccoon I found the solution :

fun Job.status(): String = when {
    isActive -> "Active/Completing"
    isCompleted && isCancelled -> "Cancelled"
    isCancelled -> "Cancelling"
    isCompleted -> "Completed"
    else -> "New"
}

enter image description here

More information in this link : https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/

Jéwôm'
  • 3,753
  • 5
  • 40
  • 73
  • 1
    You can minimize this, first row is just `isActive` and then the rest of the clauses don't need to check `isActive` at all. On the other hand, the code is open to races because you can't read the flags atomically. For example, you may paradoxically get the status "New" for a completed job. – Marko Topolnik Feb 12 '20 at 07:21
  • `isCancelled -> "Cancelling"` --- i believe this is wrong since you assume `!isCompleted` without checking it. Also, you could at least lower the odds of race conditions by reading the flags just once, before `when`. It would still not remove the problem. – Marko Topolnik Feb 12 '20 at 12:22