https://kotlinlang.org logo
#android
Title
# android
e

Ellen Spertus

04/13/2020, 10:46 PM
I have a fragment whose behavior depends on the result of looking up the launching `Intent`’s extras in a
RoomDatabase
. I can’t access the database (or even the repository) directly from the fragment’s
onStart()
method, since database access is not allowed on the UI thread. What’s the right way for
onStart()
to initiate a database query on the
IO
thread and then a callback on the UI thread?
Is this the right pattern?
Copy code
override fun onStart() {
    super.onStart()
    viewModel = buildModel()
    viewModel.viewModelScope.launch {
        checkForNickname()
    }
}

private suspend fun checkForNickname() {
    val entity = viewModel.getContact() // suspend fun
    withContext(Dispatchers.Main) {
        // do something with entity
    }
}
r

rkeazor

04/14/2020, 6:36 AM
This channel is for Kotlin related topics, this seems outside of that scope
e

Ellen Spertus

04/14/2020, 8:18 PM
@rkeazor My question does involve Kotlin. See my code sample. There are other threads on this channel that do not mention Kotlin. Perhaps you meant to leave your comment on one of those.
👍 1
2 Views