• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

200
Vistas
Kotlin: define a coroutine scope in App class

Is it a good practice to declare a coroutine scope inside the App class instead of using a Globascope?

class App : Application() {

    val applicationJob = Job()

    companion object {
        lateinit var instance: App
            private set

        lateinit var appDefaultScope: CoroutineScope
    }

    override fun onCreate() {
        super.onCreate()
        instance = this@App
        appDefaultScope = CoroutineScope(Dispatchers.Default + applicationJob)
    }

}

Here I defined a variable appDefaultScope and initialized it in the App's onCreate

So anywhere in my code I could always do:

App.appDefaultScope.launch {
   // some operations
}

The main difference with a GlobalScope that I see is that here I can always cancel the job and shut down all potentially stuck coroutines.

Are there are better alternatives to this?

The reason is that i have some object functions that use coroutines and are not called from an activity (then I cannot provide them with a scope defined inside the activity) but need a scope for their operations. An example of such object function is a Log that writes on a local database that can be called almost everywhere in the App.

over 3 years ago · Santiago Trujillo
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda