Why am I getting the log for 4 times? I don't have...
# compose
m
Why am I getting the log for 4 times? I don't have any idea what is wrong here. Can anyone help?
q
are you using collectAsState ?
m
No, I am not using collectAsState
q
if you are observing value from viewmodel or state class they you have to check when composable function is loading, is their any state change.. if you want to print log just for first time , use LaunchEffect (unit) {put logs inside this} then you will see logs print only one time ..
c
Try googling “recomposition” and “side-effects”
☝️ 1
☝🏾 1
m
Where that play quiz is just a list
Copy code
var playedQuiz = listOf<PlayedQuizModel>()
c
Sure but you have no control on how often the composable is composed. You need state, remember and side-effects to cope with that.
👍 3
q
you are listening from view model, most changes its related to compose state change and recomposition.
m
What could be the solution for this? Can i wrap my whole Scaffold tree inside of launched effect block?
Here is my navigation graph does this cause any issue
c
No, just how you do the logging is wrong. Just wrap the log call in the launch effect.
I guess you should read more on how compose works. Seems like you are missing the fundamentals. 🤔
☝️ 2
m
Okay ! thanks for you time and advice.
x
Compose is based on functions, not classes. In a class you can have a property at the beginning of the class body and you know that property will be generated only once when the class is instanced. This is not the same for functions. Compose will re-execute the function body each time a certain
@Composable
function is re-composed. To achieve the same approach as the class property, you'd use a
remember
block to tell the compiler to save that value accross recompositions and not re-execute that code. However, if what you want is to log each time that function is recomposed, then you should use a
DisposableEffect
(I don't see the need for a
LaunchEffect
here)
m
I really wish there was a “SideEffect” variation with keys, so you didn’t need the overhead of the coroutine, or the empty onDispose block.
e
Its easy to add it though 🙂