Does cancelling a coroutine cancel the write to a file?

195 Views Asked by At
suspend fun copy(oldFile: File, newFile: File): Boolean{
     return withContext(Dispatchers.IO) {
            var inputStream: InputStream? = null
            var outputStream: OutputStream? = null
            try {
                val fileReader = ByteArray(4096)
                inputStream = oldFile.inputStream()
                outputStream = FileOutputStream(newFile)
                while (true) {
                    val read: Int = inputStream.read(fileReader)
                    if (read == -1) {
                        break
                    }
                    outputStream.write(fileReader, 0, read)
                }
                outputStream.flush()
                true
            } catch (e: IOException) {
                Log.e(TAG, "${e.message}")
                false
            } finally {
                inputStream?.close()
                outputStream?.close()
            }
        }

}

In the above code, if I cancel the job that is running the function, does the copying gets cancelled or do I have to manually check for state of the job inside while loop using ensureActive()?

0

There are 0 best solutions below