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

Vitaliy Zarubin

05/28/2021, 2:35 PM
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

nitrog42

05/28/2021, 2:59 PM
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

Vitaliy Zarubin

05/28/2021, 3:02 PM
👍 1
a

Adam Powell

05/28/2021, 3:24 PM
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

Vitaliy Zarubin

05/28/2021, 3:28 PM
little silly
Why? Isn't it the same thing?
a

Adam Powell

05/28/2021, 3:29 PM
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

Vitaliy Zarubin

05/28/2021, 3:48 PM
I think this is it. But how is this to be understood? How to learn to understand bytecode? 🙂
a

Adam Powell

05/28/2021, 3:58 PM
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

Vitaliy Zarubin

05/28/2021, 4:02 PM
Got it. Thank you.
👍 1
👍🏼 1