https://kotlinlang.org logo
#compose
Title
# compose
f

Filip Stanis

02/07/2022, 4:42 PM
Wrapping a
Flow<List<Entity>>
I get from Room into either a
SharedFlow
or a
StateFlow
seems to prevent it from working (I get the initial list of items from Room, but it never updates). What could be causing this? (code in first reply)
In my composable:
val state = viewModel.state.collectAsState(State())
in every situation.
Copy code
// This works as expected
val state = repository.getAll().map { State(items = it) }

// StateFlow - this doesn't
val state = repository.getAll().map { State(items = it) }.stateIn(viewModelScope, WhileSubscribed(5000), State())

// SharedFlow - same as StateFlow
val state = repository.getAll().map { State(items = it) }.shareIn(viewModelScope, WhileSubscribed(5000), 1)
(I'm aware I'm exposing a mutable flow here, that's just to keep the example simple)
c

corneil

02/07/2022, 4:59 PM
How are you updating the state at source?
f

Filip Stanis

02/07/2022, 5:03 PM
it's directly from my Room DAO:
Copy code
interface MyDao {
    @Query("SELECT * FROM Entity ORDER BY timestamp DESC")
    fun getAll(): Flow<List<Entity>>
}
c

corneil

02/07/2022, 5:42 PM
Shouldn't you be using
getAll().collect
in order to let the flow emit values.
f

Filip Stanis

02/07/2022, 5:51 PM
OK, I found the issue is because I forgot to make my repository / DB a
@Singleton
. Why this caused an issue only for a
StateFlow
/
stateIn
is a mystery.
c

Chris Fillmore

02/08/2022, 3:24 PM
For future reference there is #room
f

Filip Stanis

02/08/2022, 3:36 PM
Thanks, I was convinced this is a compose / flow issue when I wrote it 😕
3 Views