SimpleStorage icon indicating copy to clipboard operation
SimpleStorage copied to clipboard

Fully support coroutines

Open NinoDLC opened this issue 1 year ago • 0 comments

First I want to thank you a lot for this library ! Scoped Storage is such a mess, and you provide a lot of help. 🙏

What feature you want to suggest? Expose suspending functions that return the result of the operation without using callbacks. It would be usefull for DDD / Clean architecture where Structured Concurrency is much needed.

Your solution A simple example, the API would be something like

suspend fun DocumentFile.copyFolderTo(
    context: Context,
    targetParentFolder: DocumentFile,
    skipEmptyFiles: Boolean = true,
    newFolderNameInTargetPath: String? = null, 
    // No callbacks since it makes no sense in suspending functions
) : FolderResult // Sealed class with Success/Failed for example or whatever

Your current alternative Far from perfect, but at least it suspends until work is finished and I get the success status as a Boolean

suspend fun doStuff(uri: Uri): Boolean = withContext(Dispatchers.IO) {
    val sourceDocumentFile = DocumentFile.fromTreeUri(application, uri) ?: return false
    
    return suspendCancellableCoroutine { cont ->
        sourceDocumentFile.copyFolderTo(
            context = application,
            targetParentFolder = DocumentFile.fromFile(internalApplicationFolderFile),
            callback = object : FolderCallback() {
                override fun onCompleted(result: Result) {
                    cont.resume(true)
                }

                override fun onFailed(errorCode: ErrorCode) {
                    cont.resume(false)
                }
            }
        )
    }
}

NinoDLC avatar Apr 30 '24 18:04 NinoDLC