https://kotlinlang.org logo
#coroutines
Title
# coroutines
j

Jay

03/16/2019, 12:43 PM
When testing coroutines, is there a way to get notified on each context switch?
l

louiscad

03/16/2019, 2:45 PM
What's the use case?
d

Dico

03/16/2019, 4:46 PM
If you mean thread context switch, you can try
ThreadContextElement
.
j

Jay

03/16/2019, 7:41 PM
My specific use case here is to test that a presenter behaves correctly while data is loading. When the context switches to IO, the loading indicator should be activated, and after the coroutine finishes it should be deactivated. I was able to do this (in this case) because for tests I’m injecting a context provider object (with Unconfined supplied for all contexts), and I added a callback when the IO context was requested. However, this only works because launch is on the main context, then the loading is done withContext IO in the implementation. An implementation that launched on IO and switched to Main to set the loading indicator each time would confuse my test and it would fail. If there was a way to get a callback each time the internal state machine moved to the next step, I could put my assertions there.
3 Views