Skip to content

Instantly share code, notes, and snippets.

@Andrew0000
Created February 26, 2025 17:44
Show Gist options
  • Save Andrew0000/5b090f4206b8fe0528d24ab9d40f0c63 to your computer and use it in GitHub Desktop.
Save Andrew0000/5b090f4206b8fe0528d24ab9d40f0c63 to your computer and use it in GitHub Desktop.
DiskDataSource - utility functions for working with files via Okio
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.withContext
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import kotlinx.serialization.encodeToString
import okio.Path
object DiskDataSource {
val json = Json {
ignoreUnknownKeys = true
}
@Throws(Exception::class)
suspend inline fun <reified T> read(path: Path): T =
withContext(Dispatchers.IO) {
val fileSystem = defaultFileSystem()
val string = fileSystem.read(path) {
this.readUtf8()
}
json.decodeFromString<T>(string)
}
@Throws(Exception::class)
suspend inline fun readBytes(path: Path): ByteArray =
withContext(Dispatchers.IO) {
defaultFileSystem().read(path) {
this.readByteArray()
}
}
@Throws(Exception::class)
suspend inline fun <reified T> write(path: Path, content: T) =
withContext(Dispatchers.IO) {
val fileSystem = defaultFileSystem()
val parent = path.parent
if (parent != null && !fileSystem.exists(parent)) {
fileSystem.createDirectories(parent)
}
val contentJson = json.encodeToString(content)
fileSystem.write(path) {
this.writeUtf8(contentJson)
}
}
@Throws(Exception::class)
suspend inline fun writeBytes(path: Path, content: ByteArray) =
withContext(Dispatchers.IO) {
val fileSystem = defaultFileSystem()
val parent = path.parent
if (parent != null && !fileSystem.exists(parent)) {
fileSystem.createDirectories(parent)
}
fileSystem.write(path) {
this.write(content)
}
}
@Throws(Exception::class)
suspend fun delete(path: Path) =
withContext(Dispatchers.IO) {
val fileSystem = defaultFileSystem()
if (fileSystem.exists(path)) {
fileSystem.deleteRecursively(path)
}
}
}
//
import okio.FileSystem
expect fun defaultFileSystem(): FileSystem
expect fun getBaseCacheDir(): String
//
import android.content.Context
import okio.FileSystem
actual fun defaultFileSystem(): FileSystem =
FileSystem.SYSTEM
actual fun getBaseCacheDir(): String {
return (AppConfig.context as Context).cacheDir.absolutePath
}
//
import okio.FileSystem
import platform.Foundation.NSCachesDirectory
import platform.Foundation.NSSearchPathForDirectoriesInDomains
import platform.Foundation.NSUserDomainMask
actual fun defaultFileSystem(): FileSystem =
FileSystem.SYSTEM
actual fun getBaseCacheDir(): String {
return NSSearchPathForDirectoriesInDomains(
NSCachesDirectory,
NSUserDomainMask,
true,
).first() as String
}
//
okio = { module = "com.squareup.okio:okio", version = "3.9.1" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment