Skip to content Skip to sidebar Skip to footer

Kotlin Coroutines, Continues Updates

New to kotlin, i tried many examples and tutorials to no avail, My requirement is: Ui creates a coroutine that initiates a network connection on press of a button, that coroutine

Solution 1:

From what I understand you want to create a coroutine that listens for responses over a connection. In that case the only thing that you need make sure is that the coroutine should be cancellable, once activity is closed.

suspendfunconnector() = withContext(Dispatchers.IO){
    try {
        // open the connection herewhile(isActive) {
        var doing  : String = "nothing"// fetched from a network call
              withContext(Dispatchers.Main){
                Toast.makeText(this@MainActivity2, doing, Toast.LENGTH_LONG).show()
            }
        }
    } finally {
        withContext(NonCancellable) {
            //close the connection here     
        }   
    }

isActive is an extension property available inside the coroutine via the CoroutineScope object.

When the screen is rotated, the connection is closed and a new one is being opened once the coroutine is called again in onCreate.

Post a Comment for "Kotlin Coroutines, Continues Updates"