Is this shady/wrong? Background: `onTaskSelected` ...
# coroutines
f
Is this shady/wrong? Background:
onTaskSelected
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.
Copy code
ViewModel {

init {
    if (taskIdToSelect != null && taskIdToSelect != Task.NO_ID) {
        CoroutineScope(Dispatchers.Main).launch {
            selectedTask.collect {
                onTaskSelected(taskIdToSelect.toLong())
                cancel()
            }
        }
    }
}
b
🤔 if you can collect it, why can't you call first()? I mean how collect helps you in case if flow is not initialized? Most likely
launch
helps you, not a
collect
call
f
ah good point
let me try
Nah it actually doesn't work without the collect
I don't know why
collect
works in init but
first
doesn't
b
that's strange because basically
first()
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/hacky
f
apparently, you can't call
first()
on a Flow inside an
init
block of that same object
b
Even from the launch fun? Maybe flow is declared below init block? In this case just move it to top
Could you provide minimal selft-contained example?
f
Maybe flow is declared below init block? In this case just move it to top
holy shit that actually solved it
👍 1
I'm such a noob
thank you
j
Please don't use the
CoroutineScope
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
f
gotcha