Florian
10/28/2021, 10:44 AMonTaskSelected
calls first()
on the selectedTask
flow. But apparently, I can't do that in the init
block of this ViewModel because then the Flow is not initialized yet. So the temporary collect
makes sure that the selectedTask
Flow is ready.
ViewModel {
init {
if (taskIdToSelect != null && taskIdToSelect != Task.NO_ID) {
CoroutineScope(Dispatchers.Main).launch {
selectedTask.collect {
onTaskSelected(taskIdToSelect.toLong())
cancel()
}
}
}
}
bezrukov
10/28/2021, 12:38 PMlaunch
helps you, not a collect
callFlorian
10/28/2021, 12:59 PMFlorian
10/28/2021, 12:59 PMFlorian
10/28/2021, 1:03 PMFlorian
10/28/2021, 1:03 PMcollect
works in init but first
doesn'tbezrukov
10/28/2021, 2:21 PMfirst()
does collect
inside. Maybe with collect it works because onTaskSelected is called for 2nd, 3rd,.., Nth emission?
What do you mean by "doesn't work"? is it crashes or does nothing? Anyway without understanding what's going on yes, it looks wrong/hackyFlorian
10/28/2021, 4:56 PMfirst()
on a Flow inside an init
block of that same objectbezrukov
10/28/2021, 7:14 PMbezrukov
10/28/2021, 7:14 PMFlorian
10/28/2021, 8:08 PMMaybe flow is declared below init block? In this case just move it to topholy shit that actually solved it
Florian
10/28/2021, 8:08 PMFlorian
10/28/2021, 8:08 PMJoffrey
10/29/2021, 8:01 AMCoroutineScope
factory function this way, you need to store that scope somewhere and cancel it appropriately when your component's lifecycle ends. In this case, it seems you are in a view model so you should have access to viewModelScope
Florian
11/02/2021, 6:31 PM