Skip to content

Instantly share code, notes, and snippets.

@ZacSweers
Created September 16, 2018 06:02
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZacSweers/0dfa1b38f23558cfd1a0a391cfab3542 to your computer and use it in GitHub Desktop.
Save ZacSweers/0dfa1b38f23558cfd1a0a391cfab3542 to your computer and use it in GitHub Desktop.
Okio/AtomicFile interop kotlin extensions
import android.util.AtomicFile
import okio.Buffer
import okio.Sink
import okio.sink
import okio.source
import java.io.FileOutputStream
import java.io.IOException
fun AtomicFile.source() = openRead().source()
fun AtomicFile.sink(): Sink {
return object : Sink {
val fos: FileOutputStream = startWrite()
val sink: Sink = fos.sink()
var terminated = false
override fun write(source: Buffer, byteCount: Long) {
guardedIo {
sink.write(source, byteCount)
}
}
override fun flush() {
guardedIo {
sink.flush()
}
}
override fun timeout() = sink.timeout()
override fun close() {
guardedIo {
finishWrite(fos)
}
terminated = true
}
private fun <T> guardedIo(block: () -> T): T {
if (terminated) throw IOException("terminated")
try {
return block()
} catch (e: IOException) {
terminated = true
failWrite(fos)
throw e
}
}
}
}
@ZacSweers
Copy link
Author

Note most of this design is by @swankjesse!

@Egorand
Copy link

Egorand commented Sep 16, 2018

Inline guardedIo()?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment