I’m working on an Android app and I launch a corou...
# coroutines
z
I’m working on an Android app and I launch a coroutine using GlobalScope at the start of my application, that coroutine then uses a flow to emit a value every 30 seconds for the lifetime of my application. I know that GlobalScope is generally not recommended, what should I be using instead?
n
Sounds like you are using it correctly.
👍 1
In a custom Application class or a singleton, that’s usually what you want. The warning is there because a lot of people will use it in other situations that should have shorter lifetimes than the process.
z
One thing I have noticed is that I’m seeing non fatal job cancellation exceptions in fabric which I think are when the user closes the app. Are coroutines launched with global scope meant to handle the cancellation exception?
n
I’m guessing you have some “catch everything and log to fabric” block. If you have exception handling code, you generally want to ignore those cancellation exceptions and just rethrow them.
l
Alternatively you can use the approach outlined here
Copy code
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class ApplicationScope

@InstallIn(SingletonComponent::class)
@Module
object CoroutinesScopesModule {

@Singleton
@ApplicationScope
@Provides
fun providesCoroutineScope(
    @DefaultDispatcher defaultDispatcher: CoroutineDispatcher
): CoroutineScope = CoroutineScope(SupervisorJob() + defaultDispatcher)
}
Then just
@Inject @ApplicationScope lateinit var appScope: CoroutineScope
into application class