Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I restart canceled job? #81

Closed
Bill-Park opened this issue Jul 7, 2017 · 2 comments
Closed

How can I restart canceled job? #81

Bill-Park opened this issue Jul 7, 2017 · 2 comments

Comments

@Bill-Park
Copy link

After cancel job, how can I restart?
This is my code. (kotlin)

send_udp_repeat = launch(CommonPool) {
            var nextPrintTime = System.currentTimeMillis()
            while (isActive) {
                val currentTime = System.currentTimeMillis()
                if (currentTime >= nextPrintTime) {
                    sendUDPrequest(UDP_SERVER_IP, UDP_SERVER_PORT, UDP_SERVER_MSG)
                    nextPrintTime = currentTime + 2000L
                }
            }
        }
commu_status.setOnClickListener {
            if (send_udp_repeat.isActive == true) {
                send_udp_repeat.cancel()
            }
        }
menu_button.setOnClickListener {
            // I want to restart send_udp_repeat here
        }
@elizarov
Copy link
Contributor

elizarov commented Jul 7, 2017

If you are running it all from UI thread, then it is quite easy via a bit of abstraction. You should just introduce a function to restart your coroutine. Select the block of code that is to the right of send_udp_repeat and press (Ctrl/Cmd-Shfit-M) to introduce a function:

fun launchSendUpdRepeat() = launch(CommonPool) {
            var nextPrintTime = System.currentTimeMillis()
            while (isActive) {
                val currentTime = System.currentTimeMillis()
                if (currentTime >= nextPrintTime) {
                    sendUDPrequest(UDP_SERVER_IP, UDP_SERVER_PORT, UDP_SERVER_MSG)
                    nextPrintTime = currentTime + 2000L
                }
            }
        }

send_udp_repeat = launchSendUdpRepeat()

Then change send_udp_repeat to a nullable type and rewrite your click listeners (note that you don't have to check for isActive):

commu_status.setOnClickListener {
            send_udp_repeat?.cancel()
            send_udp_repeat = null
        }
menu_button.setOnClickListener {
            send_udp_repeat = launchSendUdpRepeat()
        }

@elizarov elizarov closed this as completed Jul 7, 2017
@Bill-Park
Copy link
Author

It works for me.
Thanks you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants