Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

114
Vistas
Specify an existing LiveData object for the liveData kotlin builder function

For example, we can create a LiveData object using a liveData builder function:

var liveData: LiveData<String> = liveData(Dispatchers.IO) {
    delay(1000)
    emit ("hello")

    delay(1000)
    emit ("world")
}

This is useful in ViewModel, I create a LiveData object that receives multiple data values from an asynchronous heavy function in one line.

But what if I already have a MutableLiveData object and just want to post values there, without creating a new LiveData object? How can I do this?

I need a way to asynchronously emit multiple values into existed MutableLiveData object inside a ViewModel scope to automatically finish all running tasks when the ViewModel will be cleared.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You can post to a MutableLiveData in a coroutine launched from viewModelScope.

private val myMutableLiveData = MutableLiveData<String>()

fun someFun() {
    viewModelScope.launch {
        myMutableLiveData.value = “Hello”
        delay(500L)
        myMutableLiveData.value = “World”

        myMutableLiveData.value = someSuspendFunctionRetriever()

        val result = withContext(Dispatchers.IO) {
            someBlockingCallRetriever()
        }
        myMutableLiveData.value = result

        // or use post() when not on Main dispatcher:
        withContext(Dispatchers.IO) {
            val result = someBlockingCallRetriever()
            myMutableLiveData.post(result)
        }
    }
}
over 4 years 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 vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda