Created
March 2, 2022 20:37
-
-
Save raystatic/cf4e6538ccc20056955a86d955ca8cdd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private fun startDownloadingFile( | |
file: File, | |
success:(String) -> Unit, | |
failed:(String) -> Unit, | |
running:() -> Unit | |
) { | |
val data = Data.Builder() | |
data.apply { | |
putString(FileDownloadWorker.FileParams.KEY_FILE_NAME, file.name) | |
putString(FileDownloadWorker.FileParams.KEY_FILE_URL, file.url) | |
putString(FileDownloadWorker.FileParams.KEY_FILE_TYPE, file.type) | |
} | |
val constraints = Constraints.Builder() | |
.setRequiredNetworkType(NetworkType.CONNECTED) | |
.setRequiresStorageNotLow(true) | |
.setRequiresBatteryNotLow(true) | |
.build() | |
val fileDownloadWorker = OneTimeWorkRequestBuilder<FileDownloadWorker>() | |
.setConstraints(constraints) | |
.setInputData(data.build()) | |
.build() | |
workManager.enqueueUniqueWork( | |
"oneFileDownloadWork_${System.currentTimeMillis()}", | |
ExistingWorkPolicy.KEEP, | |
fileDownloadWorker | |
) | |
workManager.getWorkInfoByIdLiveData(fileDownloadWorker.id) | |
.observe(this){ info-> | |
info?.let { | |
when (it.state) { | |
WorkInfo.State.SUCCEEDED -> { | |
success(it.outputData.getString(FileDownloadWorker.FileParams.KEY_FILE_URI) ?: "") | |
} | |
WorkInfo.State.FAILED -> { | |
failed("Downloading failed!") | |
} | |
WorkInfo.State.RUNNING -> { | |
running() | |
} | |
else -> { | |
failed("Something went wrong") | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment