I am trying to get data from a room database via a...
# coroutines
d
I am trying to get data from a room database via a Flow. I want to make access to this data instant so I am thinking of using a StateFlow to access the state from memory via StateFlow.value. So on app start I want to be able to access the StateFlow.value to get the initial value from the database maybe via a blocking suspend function. What does this look like and any recommendations?
s
If it is getting data, then use a suspend fun with a return value that contains the data of the database. If it is continuous listening to changes of data in a database, then use a Flow.
d
I have 3 use cases • Flow where I am observing data from room and reactively updating • suspend where I am optimally using this for single shot things. • So then I have cases where I cant really use a suspend function. So lets say I need the data in an interceptor or in some sort of third party library callback where I can not make it a suspend function because I need to return the data as the result of the function.
Basically its login session so its a very small amount of data I want to have in memory. So pull from cache in memory and can observe from flow
Copy code
var stateFlow = MutableStateFlow(runBlocking { loginSessionFlow().first() })
loginSessionFlow().collect {
    stateFlow.emit(it)
}
Is above what I was thinking but I would either I am thinking about things wrong or there may be a better way to do this
n
Take a look at
stateIn
stateIn
will work for places where you want the data immediately but because you are dealing with data where there is no immediate value available initially, any code that needs data immediately will need to contend with the possibility that the data was not loaded yet. This can often be represented with an initial null value. For places where you can block to get the data, you can call
runBlocking
there and then use the suspend APIs to get the value. Calling
runBlocking
to create the
MutableStateFlow
is likely to cause issues since anything using it (presumable coroutines) will then be dependent on blocking code.
117 Views