It's good way? Dao Room ```@Query("SELECT * FROM M...
# compose
v
It's good way? Dao Room
Copy code
@Query("SELECT * FROM ModelRepo WHERE id = :id")
fun getModel(id: Long): Flow<ModelRepo>
ViewModel
Copy code
val findByIdRepo: (Long) -> Flow<ModelRepo?> = { id -> dataRepo.getModel(id).distinctUntilChanged() }
@Composable
Copy code
val model: ModelRepo? by viewModel.findByIdRepo(repoId).collectAsState(initial = null)
βž• 1
🚫 1
n
I will just say that
Copy code
val findByIdRepo: (Long) -> Flow<ModelRepo?> = { id -> dataRepo.getModel(id).distinctUntilChanged() }
should probably just be a method :
Copy code
fun findByIdRepo(id: Long): Flow<ModelRepo?> = dataRepo.getModel(id).distinctUntilChanged()
πŸ™‚ 1
πŸ™ 1
v
πŸ‘ 1
a
The
@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.
βž• 1
πŸ™ 2
You can solve this by remembering the flow you use unless the viewModel or the repoId change:
Copy code
val model by remember(viewModel, repoId) {
  viewModel.findByIdRepo(repo)
}.collectAsState(null)
πŸ™ 1
additionally it seems a little silly to use a function val for
findByIdRepo
instead of a normal function there, but that won't affect correctness, just add a little overhead
βž• 1
v
little silly
Why? Isn't it the same thing?
a
Check
View Kotlin bytecode
on each approach in the IDE πŸ™‚
βž• 1
πŸ™‚ 1
for most situations on android (combinations of kotlin compiler, d8 desugaring of openjdk8 language features, the specific device OS version) the val + lambda version ends up creating a separate object with an
invoke()
method as opposed to a plain final function call
πŸ™ 1
v
I think this is it. But how is this to be understood? How to learn to understand bytecode? πŸ™‚
a
If you hit that "Decompile" button at the top it'll show something more java-like. Note that it's created a getter for a function object
you'll also want to look at the difference between the code that calls this function
v
Got it. Thank you.
πŸ‘ 1
πŸ‘πŸΌ 1