Ktor: delete temporary file after response is sent

Viewed 183

I'm sending a temporary file as a response to a request using the ktor library on a android tablet, but I can't find a way to safe delete it after being sent (or something went wrong).

How can I make sure that this file was delete without interrupting the sending process? Maybe using some callback or method that I´m not aware of.

Update: answering comments:

my code:

try {
    call.response.headers.append("entity-count", entityCount)
    call.response.headers.append("sync-length", lenght)
    call.respondFile(FileContent(file) // need to delete this file after sent OR failed
} catch (e: Exception) {
    Log.e(TAG, e)
}

should I just add a file.delete() line inside a finally block?

I think my main question/confusion (coming from java world) its if respondFile is a blocking call or not. If it its, just adding file.delete on finally block will be fine, otherwise I need to register somme kind of onCompleted callback.

1 Answers

You can use finally: it will be called after sending the file or in case of an error

try {
    call.response.headers.append("entity-count", entityCount)
    call.response.headers.append("sync-length", lenght)
    call.respondFile(FileContent(file) // need to delete this file after sent OR failed
} catch (e: Exception) {
    Log.e(TAG, e)
} finally {
    file.delete()
}
Related