0
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()?

Diken Mhrz
  • 327
  • 2
  • 14
  • 1
    No, copying will not be cancelled. – bylazy Nov 15 '22 at 07:28
  • will there be any suspension points? – Diken Mhrz Nov 15 '22 at 09:12
  • 1
    There are no calls to any of the suspend functions here, so all code will run to the end or until some exception occurs. The "Finally" block will work anyway. – bylazy Nov 15 '22 at 10:22
  • So I am confused on why Dispatchers.IO is preferred if there aren't any suspend functions being called... Could you please explain why Dispatchers.IO are used for copying of file? – Diken Mhrz Nov 15 '22 at 10:24
  • 1
    Its purpose is to run blocking code off the UI thread. – bylazy Nov 15 '22 at 10:31
  • So if we are using coroutines, can you think of any scenario where managing multiple threads are better than just dispatching it to Dispatchers.Default or Dispatchers.IO? – Diken Mhrz Nov 16 '22 at 05:13
  • 1
    Yes, for example, threads are preferable for heavy calculations. Coroutines are designed for tasks that wait for something most of the time, like some API responses. – bylazy Nov 16 '22 at 05:24
  • Since Dispatchers.Default or Dispatcher.IO will switch to another thread anyway, is it necessary to create a new thread ourself? – Diken Mhrz Nov 18 '22 at 18:04
  • Why? Unless you need to copy tons of files asynchronously, while some other I/O operations must be performed in parallel. – bylazy Nov 18 '22 at 18:43

0 Answers0