Skip to content

Commit

Permalink
refactor: connection callback when downloading
Browse files Browse the repository at this point in the history
  • Loading branch information
CraZyLegenD committed Oct 16, 2020
1 parent 4ecfb67 commit 0bfe8dd
Showing 1 changed file with 7 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -337,16 +337,19 @@ fun downloadFile(urlPath: String, localPath: String, callback: (Uri?) -> Unit =
return uri
}

fun downloadFileWithProgress(urlPath: String, localPath: String, onError: () -> Unit = {}, progress: (Int) -> Unit = {}, callback: (Uri?) -> Unit = {}) {
fun downloadFileWithProgress(urlPath: String, localPath: String,
connectionCallBack: (responseCode: Int) -> Unit = {},
onError: (Exception) -> Unit = {}, progress: (Int) -> Unit = {}, callback: (Uri?) -> Unit = {}) {
val uri = localPath.toFile().toUri()
val connection = URL(urlPath).openConnection() as HttpURLConnection
val input = connection.inputStream
val output = FileOutputStream(uri.toFile())
try {
connection.connect()

if (connection.responseCode != HttpURLConnection.HTTP_OK) {
onError()
val responseCode = connection.responseCode
connectionCallBack(responseCode)
if (responseCode != HttpURLConnection.HTTP_OK) {
return
}

Expand All @@ -361,7 +364,7 @@ fun downloadFileWithProgress(urlPath: String, localPath: String, onError: () ->
output.write(data, 0, count)
}
} catch (e: Exception) {
onError()
onError(e)
return
} finally {
tryOrIgnore {
Expand Down

0 comments on commit 0bfe8dd

Please sign in to comment.