Skip to content

Instantly share code, notes, and snippets.

@G00fY2
Last active March 11, 2024 09:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save G00fY2/21781d271c57442a413313d4f6992bc1 to your computer and use it in GitHub Desktop.
Save G00fY2/21781d271c57442a413313d4f6992bc1 to your computer and use it in GitHub Desktop.
@Module
@InstallIn(SingletonComponent::class)
internal object DataStoreModule {
@Provides
@Singleton
fun provideMyCacheDataStore(
@ApplicationContext context: Context,
moshi: Moshi,
): DataStore<MyCachedDataClass> {
return DataStoreFactory.create(
produceFile = { context.dataStoreFile("MY_CACHE_DATA_SOURCE.json") },
serializer = DataStoreJsonSerializer(
defaultValue = MyCachedDataClass(),
provideJsonAdapter = { moshi.adapter(MyCachedDataClass::class.java) },
),
corruptionHandler = ReplaceFileCorruptionHandler { MyCachedDataClass() },
)
}
}
class DataStoreJsonSerializer<T>(
override val defaultValue: T,
// use function to provide moshi adapter to prevent initiating on main thread
private val provideJsonAdapter: () -> JsonAdapter<T>,
) : Serializer<T> {
override suspend fun readFrom(input: InputStream): T {
return try {
input.source().buffer().use {
checkNotNull(provideJsonAdapter().fromJson(it))
}
} catch (e: Exception) {
logInfo(e) { "Unable to read datastore" }
throw CorruptionException("Unable to read datastore", e) // handled by corruptionHandler
}
}
override suspend fun writeTo(t: T, output: OutputStream) {
try {
output.sink().buffer().use {
provideJsonAdapter().toJson(it, t)
}
} catch (e: Exception) {
logError(e) { "Unable to write to datastore" }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment