How to pause and resume coroutine in Kotlin?

295 Views Asked by At

I have a kotlin code like following.

private val faceProcessorFlow = MutableSharedFlow<Pair<EnrollmentModel.Waiting, Int>>()
    
init {
    viewModelScope.launch(IO) {
         faceProcessorFlow
              .onEach {
                    performEnrollment(it)
               }.collect()
    }
}
    
fun start(){
    itemsToDetect.forEach { (index, itemToDetect) ->
         viewModelScope.launch(IO) {
             val item = (itemToDetect as? EnrollmentModel.Waiting)
             if (item != null)
                  faceProcessorFlow.emit(item to index)
             else
                  updateUI()
          }
    }
}

Once the start method is called, it takes pretty long time. Well, it depends on the size of itemsToDetect. I just want to stop and resume this task when it needs. I have been searching similar solutions but they are not proper on my case, so I ask this question with detailed code. Please help me. Please share your idea with me.

0

There are 0 best solutions below