https://kotlinlang.org logo
#coroutines
Title
# coroutines
s

Se7eN

10/01/2020, 5:29 PM
Can I make this code better?
Copy code
templatesDao.getAll().collectIndexed { index, templates ->

    templatesLiveData.value = templates
    if(index == 0) {
        val newTemplates = getTemplatesFromFirestore(templates.lastIndex)
        templatesDao.insert(newTemplates)
    }
}
Is there any function like
flow.onFirst { }
or something like that
a

ansman

10/02/2020, 12:17 AM
You can implement your own extension for this but otherwise I would say this is fine.
👍 1
t

travis

10/02/2020, 5:53 AM
Assuming the DAO is providing a sharable
Flow
, then I tend to prefer avoiding side-effects in operators. In other words, IMHO it would be nicer to have the
LiveData
conversion separate from this operator. For example:
Copy code
private val all = templatesDao.getAll()
val allLiveData = all.asLiveData()

suspend fun example() {
    val newTemplates = getTemplatesFromFirestore(all.first())
    templatesDao.insert(newTemplates)
}
👍 1
s

Se7eN

10/02/2020, 7:16 AM
I see. The only reason for using collect was because I wanted to update the list when it's first loaded. I get it now, this looks good!
👍 1
5 Views