hey, think im writing myself in a corner with our ...
# coroutines
a
hey, think im writing myself in a corner with our current async architecture simple usecase: we are getting a flow from a database, and want to observe it as livedata. however, getting this flow requires data from another base, so the function to get this flow looks like
Copy code
suspend fun getBalanceFlow(): Flow<Double> {
   val session = sessionDao.getCurrentSession() // suspend fun
   return balanceDao.getBalanceFlow(session.userId)
}
in the viewmodel, we cant write
Copy code
val balance = getBalanceFlow().asLivedata()
because getBalanceFlow must be a suspend function! any way around this?
c
Since you’re returning a flow,
getBalanceFlow()
should not be marked with
suspend
. You should try to rewrite that function so that the initial
getCurrentSession()
call happens within the flow, instead of being needed to create the flow. This can usually be done pretty easily by creating a
flow{ }
and using
emitAll
with the upstream flow:
Copy code
ffun getBalanceFlow(): Flow<Double> {
    return flow {
        val session = sessionDao.getCurrentSession() // suspend fun
        emitAll(balanceDao.getBalanceFlow(session.userId))
    }
}
a
whoa
thank you!
c
The only thing to watch for with this kind of wrapping logic is to respect the execution context of the flow. https://elizarov.medium.com/execution-context-of-kotlin-flows-b8c151c9309b
a
oh interesting.. am i understanding correctly that, if as it happens
getCurrentSession()
contains code wrapped in
withContext(<http://Dispatchers.IO|Dispatchers.IO>)
, that would be a problem?
or maybe not.. since it doesnt emit anything itself
c
No, that would be fine, there’s a snippet in the article showing exactly that
That’s correct, because
getCurrentSession()
does not emit anything
Just don’t wrap the entire flow’s block in
withContext()
a
cool, thanks
doesnt seem too prohibitive
c
Yeah, it’s not difficult to work around, just something to keep in mind. And the Flow APIs will throw errors if you break this rule too, which is nice