Last active
March 11, 2024 09:43
-
-
Save G00fY2/21781d271c57442a413313d4f6992bc1 to your computer and use it in GitHub Desktop.
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
@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