how to pause and resume a kotlin coroutine when touching a view?

Viewed 4622

In my app I want to display a splash screen and after 4 seconds go to HomeActivity. However, I would like to pause the execution by touching imageview imageSplash and resume when releasing. How to do this?

                    GlobalScope.launch(context = Dispatchers.Main) {
                        imageSplash.setOnTouchListener { view, motionEvent ->
                            when(motionEvent.action){
                                MotionEvent.ACTION_DOWN ->{

                                    true
                                }
                                MotionEvent.ACTION_UP->{
                                    true
                                }
                                else ->{
                                    false
                                }
                            }
                        }
                        delay(4000)
                        val intent = Intent(this@SplashActivity, HomeActivity::class.java)
                        startActivity(intent)
                        finish()
                    }
2 Answers

Kotlin coroutine is of a type kotlinx.coroutines.Job. That class does not have methods to pause or resume a job.

Alternatively:

You need to write a logic with 2 coroutines. One that starts HomeActivity after 4 seconds. Second that listens ACTION_DOWN and ACTION_UP motion events. On ACTION_DOWN you cancel the first coroutine Job, and after ACTION_UP (after N seconds) you show HomeActivity from a second coroutine.

A bit late, but hopefully it will help.

As mentioned by @I.Step, coroutines do not offer functionality for pausing and resuming so, in this case, a simple flag like var isPaused: Boolean could work. You'll just need to check it while the coroutine is running.

Example:

private var isPaused = false

GlobalScope.launch(...) {
    while (isActive)
    {
        if (!isPaused)
        {
            // do your work here
        }
    }
}

fun pause()
{
    isPaused = true
}

fun resume()
{
    isPaused = false
}
Related