Vitaliy Zarubin
05/28/2021, 2:35 PM@Query("SELECT * FROM ModelRepo WHERE id = :id")
fun getModel(id: Long): Flow<ModelRepo>
ViewModel
val findByIdRepo: (Long) -> Flow<ModelRepo?> = { id -> dataRepo.getModel(id).distinctUntilChanged() }
@Composable
val model: ModelRepo? by viewModel.findByIdRepo(repoId).collectAsState(initial = null)
nitrog42
05/28/2021, 2:59 PMval findByIdRepo: (Long) -> Flow<ModelRepo?> = { id -> dataRepo.getModel(id).distinctUntilChanged() }
should probably just be a method :
fun findByIdRepo(id: Long): Flow<ModelRepo?> = dataRepo.getModel(id).distinctUntilChanged()
Vitaliy Zarubin
05/28/2021, 3:02 PMAdam Powell
05/28/2021, 3:24 PM@Composable
code has a bug here: viewModel.findByIdRepo
is returning a new Flow
instance on each call. If .collectAsState
has a new Flow
instance to collect on a recomposition, it will cancel the old collection and start a new one fresh. This would cancel and re-start a lot of data loads if this function recomposes frequently.val model by remember(viewModel, repoId) {
viewModel.findByIdRepo(repo)
}.collectAsState(null)
findByIdRepo
instead of a normal function there, but that won't affect correctness, just add a little overheadVitaliy Zarubin
05/28/2021, 3:28 PMlittle sillyWhy? Isn't it the same thing?
Adam Powell
05/28/2021, 3:29 PMView Kotlin bytecode
on each approach in the IDE 🙂invoke()
method as opposed to a plain final function callVitaliy Zarubin
05/28/2021, 3:48 PMAdam Powell
05/28/2021, 3:58 PMVitaliy Zarubin
05/28/2021, 4:02 PM