I'm in the process of updating my Kotlin Android app to use Coroutines 1.5.2 (previously used 1.4.3).
In 1.5.2, any uses of GlobalScope.launch
are now flagged with an inspection as "delicate":
https://blog.jetbrains.com/kotlin/2021/05/kotlin-coroutines-1-5-0-released/#globalscope
Let's say I know what I'm doing (in some cases I need a scope that won't go away with the containing activity / fragment).
How do I mark these uses so they don't get flagged? The following options are suggested, but none seem good.
Option 1 - Add @DecliateCoroutinesApi
to the method. This makes the method also "delicate" and any call to that now get the inspection, so that achieves nothing.
Option 2 - Add @DecliateCoroutinesApi
to the class. Seems like overkill.
Option 3 - Add @OptIn(DelicateCoroutinesApi::class)
to the method. Almost good, but requires a special compiler switch -Xopt-in=kotlin.RequiresOptIn
. Kind of messy.
Any suggestions?
If you really know what you're doing, option 3 should be the way to go. @OptIn
is indeed experimental but that compiler flag is a small price to pay to use experimental features via @OptIn
in general. You could also not use the compiler flag, and keep the warning about the @OptIn
annotation itself, but that's even messier IMO.
That said, you should really think twice about using GlobalScope
. Most of the time you can instead create a scope that you control yourself (with a dispatcher and maybe a Job
/ SupervisorJob
as well, so you can cancel coroutines when appropriate).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.