How to convert `fun myFun(): LiveData<MyClass&g...
# coroutines
m
How to convert
fun myFun(): LiveData<MyClass>
to a suspend function that returns as soon as the LiveData value is set (i.e. the first time since LiveData created)? Note - the actual scenario is Room where I sometimes want LiveData<List> and othertimes just want the List of results, but don’t want to specify the SQL annotation twice. The best I have so far is:
Copy code
suspend fun mySuspendFun() = suspendCoroutine<List<MyClass>> { cont ->
        val live = myFun()
        live.observeForever(object: Observer<List<MyClass>> {
            override fun onChanged(it: List<MyClass>) {
                live.removeObserver(this)
                cont.resume(it)
            }
        })
    }
For starters, it seems we need a
withContext(Dispatchers.Main) {}
around the
suspendCoroutine
call because
observeForever
must be called on main thread
LiveData builders is the answer (albeit in reverse but that’s fine)! https://developer.android.com/topic/libraries/architecture/coroutines#livedata