Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

112
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda