return value from Kotlin async Coroutine

Viewed 35

I want to return value from this function which gets data from local database:

fun getAllTodo() :  LiveData<List<TodoModel>>{

   viewModelScope.launch(Dispatchers.IO) {

        val data = async { getTodoFromDB() }
        data.await()
    }
}

suspend fun getTodoFromDB(): LiveData<List<TodoModel>> {
    return database.getAll()
}

P.S: I am new to Coroutine, might have done something silly. Looking forward for Android community help

1 Answers

A value can't be returned from launched coroutine. If getTodoFromDB() returns LiveData object and is not suspend, just try to call it without launching a coroutine:

fun getAllTodo(): LiveData<List<TodoModel>> = getTodoFromDB()

If getTodoFromDB() is suspend you can use liveData builder function:

val allTodo:  LiveData<List<TodoModel>> = liveData {
   emitSource(getTodoFromDB())
}
Related