简体   繁体   中英

GlobalScope for saving files in Android

I have scenarios where I need to save some objects to disk. So far I've been doing this with Java's ExecutorService. But I'm now refactoring parts of my code to Kotlin, and was wondering whether I'm handling this right.

So in Java I have a code which goes to my Kotlin functions which are:

// Java code calls this function in KotlinUtils.kt:
fun saveFileInBackground(saveObj: Any, fileName: String) {
    GlobalScope.launch {
        saveFile(...)
    }
}

private suspend fun saveFile(data: ByteArray, ...) {
    withContext(Dispatchers.IO) {
        var file = File(....)
        if (!file.exists()) file.mkdirs()

        file.writeBytes(data)
    }
}

Now I've read this post: https://medium.com/@elizarov/the-reason-to-avoid-globalscope-835337445abc

And I still don't see a reason to avoid GlobalScope in this particular case. These file writes are something that I need on my app level, and they are not something that could be cancelled anytime after I dispatch those calls.

Another option I had in mind it to have the KotlinUtils class implement CoroutineScope and then just call launch instead of GlobalScope.launch . On second thought, that's a bit problematic, because it seems that the KotlinUtil would have to be abstract, which it cannot be (it's a @Singleton class using dagger2)

However, I'm fairly new to Kotlin and Coroutines, so perhaps I misunderstood something. Any advice would be much appreciated.

GlobalScope is a singleton and not associated with any Job. This launches top-level coroutines and highly discouraged to use because if you launch coroutines in the global scope, you lose all the benefits you get from structured concurrency

So if you know this and your task is completely independent of everything else in your application. Hereby independent, I mean, you do not want to cancel currently running tasks even if something goes wrong in other parts of your application. In this case, in my opinion, it is fine to use GlobalScope

For ex, if you call saveFileInBackground task in a loop and even though it fails in one of the iterations, you do not want to terminate the loop and want to continue with the rest of your iterations.

Another thing to keep in mind while using GlobalScope , if you mistakenly write wrong code in GlobalScope , it will stay there and will not get canceled by other parts of application which means your application will never terminate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM