Hello there, I am bit confused I was trying to exc...
# coroutines
a
Hello there, I am bit confused I was trying to excute the Result once the main job completes but it never emit inside
invokeOnCompletion
even after I surround it within coroutine
Copy code
liveData {
    val mainJob = viewModelScope.launch {
           emit(Result.LOADING)
           repo.add(data)
          
    }
    mainJob.join()
    mainJob.invokeOnCompletion {
        viewModelScope.launch {
        if(it != null) emit(Result.FAILED(it) else emit(Result.SUCCESS(null)
        } 
     }
}
Alternatively if I do
Copy code
liveData {
   val mainJob = viewModelScope.launch {
            emit(Result.LOADING)
            repo.add(data)
            emit(Result.SUCCESS(null)
           
     }
     mainJob.join()
}
But I need to handle if it complete with in failure or success
n
The
liveData
coroutine has finished so
emit
is throwing a CancellationException. I'd suggest avoiding viewModelScope from inside a
liveData
lambda. You can just do:
Copy code
liveData {
    coroutineScope {
    val mainJob = launch {
           emit(Result.LOADING)
           repo.add(data)
          
    }
    mainJob.join()
    mainJob.invokeOnCompletion {
        launch {
            if(it != null) emit(Result.FAILED(it)) else emit(Result.SUCCESS(null))
        } 
    }
    }
}
to get it working.
I'd probable go with something more like:
Copy code
liveData {
    emit(Result.LOADING)
    try {
        repo.add(data)
        emit(Result.SUCCESS(null)
    } catch (t: Throwable) {
        emit(Result.FAILED(t)
        throw t
    }
}
a
Oh , my bad I never thought this was the problem 😅 Thanks @Nick Allen