Android. How to correctly use viewModelScope?

172 views Asked by At

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.

1

There are 1 answers

0
LordRaydenMK On

Give two different suspend functions:

suspend fun first(): Int = TODO()

suspend fun second(): String = TODO()

that do two independent things, which you can execute separately.

To execute them in concurrently you can do:

suspend fun firstAndSecond(): Pair<Int, String> = coroutineScope {
    val r1 = async { first() }
    val r2 = async { second() }
    r1.await() to r2.await()
}

More info here.

An alternative solution, which is a higher level API on top of the solution above is using parZip from Arrow

suspend fun firstAndSecond(): Pair<Int, String> = parZip(
    first(),
    second()
) { r1, r2 -> r1 to r2 }