blocking corountine scope
See original GitHub issueHi in order to simplify unit testing I am trying to get changable context of the Corountene context like below (I am able to change context from test method)
object MyGlobalContext : CoroutineScope { var context : CoroutineContext = Dispatchers.Default override val coroutineContext: CoroutineContext get() = context }
Hovewer I am wondering weather it is possible to make averything created on the MyGlobalContext (like MyGlobalContext.launch; MyGlobalContext.actor etc) to run as runBlocking in order to make the methods synchronous for test purposes?
Issue Analytics
- State:
- Created 4 years ago
- Comments:6 (3 by maintainers)
Top Results From Across the Web
Coroutines: runBlocking vs. coroutineScope - Baeldung
Both runBlocking and coroutineScope are coroutine builders, which means they are used to launch coroutines, but we use them in different ...
Read more >Coroutines: runBlocking vs coroutineScope - Stack Overflow
runBlocking is a low-level construct, to be used only in framework code or self-contained examples like yours. · coroutineScope is a user-facing ...
Read more >Coroutines basics - Kotlin
The main difference is that the runBlocking method blocks the current thread for waiting, while coroutineScope just suspends, releasing the ...
Read more >runBlocking in Kotlin Coroutines with Example - GeeksforGeeks
Runs a new coroutine and blocks the current thread interruptible until its completion. This function should not be used from a coroutine.
Read more >Kotlin Coroutines: coroutineScope vs. runBlocking (Tutorial)
To keep it simple: runBlocking blocks, and coroutineScope suspends, and for that reason, runBlocking is a normal function, ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Here are 2 examples below that show you what you can do, hopefully that helps.
The issue you are seeing is that your assertEquals is not going to wait for the coroutine to have completed. Also you can problems for yourself modifying state outside a coroutine unless you are using the correct patterns to do so.
This is exactly why the concept of a “global scope” is discouraged. If you change your
TestClass
to inject the dispatcher or context to use via the constructor, like so:Then your test can simply inject
Dispatchers.Unconfined
and you’ll have the behavior you’re looking for: