Created
September 16, 2018 06:02
-
-
Save ZacSweers/0dfa1b38f23558cfd1a0a391cfab3542 to your computer and use it in GitHub Desktop.
Okio/AtomicFile interop kotlin extensions
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
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 | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note most of this design is by @swankjesse!