I'm trying to call 2 parallel task in my view model. Here is my code:
fun init {
viewModelScope.launch(genericErrorHandler) {
launch {
interactor1.task()
// handle result here
}
launch {
interactor2.task()
// handle result here
}
}
}
The problem is that initially I need to perform these tasks in parallel, but in some cases each one separately. In order not to duplicate the code, I want to put the call of each task into a separate method. For example:
fun init() {
viewModelScope.launch(genericErrorHandler) {
launch { runFirstInteractorTask() }
launch { runSecondInteractorTask() }
}
}
fun runFirstInteractorTask() {
viewModelScope.launch {
interator1.task()
}
}
fun runSecondInteractorTask() {
viewModelScope.launch {
interator2.task()
}
}
Will such an implementation differ from the first version, that is, does it affect the fact that I use viewModelScope for each task ? Please help me.
UPD: I need to run two tasks in parallel, while not waiting for the completion of two tasks, but processing the results as they come.
But for example, the user can click on a button that should start the execution of only one specific task.
Give two different suspend functions:
that do two independent things, which you can execute separately.
To execute them in concurrently you can do:
More info here.
An alternative solution, which is a higher level API on top of the solution above is using
parZipfrom Arrow