Pick the fix
The Room query re-runs on every rotation. Which change stops that while still stopping in the background?
class NotesViewModel(dao: NoteDao) : ViewModel() {
val notes: StateFlow<List<Note>> = dao.observeAll()
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), emptyList())
}Hint 1 of 1
How long does a rotation take?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A Use SharingStarted.WhileSubscribed(5_000)
Correct. The 5 s grace period outlasts a rotation, so the upstream keeps running across it.
Why not the others?
- B Use
SharingStarted.Eagerly. That stops the restart but also keeps the query running in the background forever. - C Collect the DAO flow directly in the Activity. Then every new Activity starts its own query.
- D Add
.distinctUntilChanged()before stateIn. That removes duplicate values; the restart still happens.