Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

55
Vistas
Kotlin CoroutineScope initialization depending upon CoroutineContext with custom getter

The google codelab Android Room with a View - Kotlin has the following snippet:

class WordViewModel(application: Application) : AndroidViewModel(application) {

    // ...

    private val coroutineContext: CoroutineContext
       get() = parentJob + Dispatchers.Main

    private val scope = CoroutineScope(coroutineContext)

    // ...

}

And from what I understand from this answer, the custom getter is evaluated everytime, whereas the assignment is evaluated at the time of constructing only. So in effect, scope would take a value that wouldn't change later, so what use is the custom getter for coroutineContext?

8 months ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

I think in this example we can get rid of

private val coroutineContext: CoroutineContext
   get() = parentJob + Dispatchers.Main

and just write

private val scope = CoroutineScope(parentJob + Dispatchers.Main)

So the result code will look like:

class WordViewModel(application: Application) : AndroidViewModel(application) {
    private var parentJob = Job()
    private val scope = CoroutineScope(parentJob + Dispatchers.Main)
    // ...
}

I guess it is a matter of style to write getter in this case. Nothing will change if we remove it.

8 months ago · Santiago Trujillo Denunciar

0

The definition of coroutineContext as a computed property (or custom getter) makes more sense when you are defining a CoroutineScope in a component with lifecycle (i.e. Android Activity). The example in the Javadoc is self-explanatory:

class MyActivity : AppCompatActivity(), CoroutineScope {
    lateinit var job: Job
    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        job = Job()
    }

    override fun onDestroy() {
        super.onDestroy()
        job.cancel() // Cancel job on activity destroy. After destroy all children jobs will be cancelled automatically
    }
}

In this case, you are creating the Job in a lifecycle method, that's why you need the computed property to return the coroutineContext with the Job instance created in onCreate.

8 months ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

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