LouisCAD / Splitties

A collection of hand-crafted extensions for your Kotlin projects.
https://splitties.louiscad.com
Apache License 2.0
2.53k stars 159 forks source link

Add suspend room db accessor #115

Open LouisCAD opened 6 years ago

LouisCAD commented 6 years ago

Example of home grown technique:

private val someDb by lazy { roomDb<SomethingDatabase>("something") }
suspend fun someDb() = withContext(ioDispatcher) { someDb }

With such a function:

suspend operator fun <T : RoomDatabase> Lazy<T>.invoke(): T = if (isInitialized()) value
else withContext(ioDispatcher) { value }

this can be reduced to this:

val someDb = lazy { roomDb<SomethingDatabase>("some") } // Client code
LouisCAD commented 6 years ago

The suspend operator fun invoke should be put in a sub-package named lazydb so it looks obvious from the imports

LouisCAD commented 6 years ago

Here's an implementation of this issue in the sample sources: https://github.com/LouisCAD/Splitties/blob/8510b5acb1c957084b00c4830011424aba3f5e95/sample/src/main/java/com/louiscad/splittiessample/extensions/coroutines/SuspendLazyRoom.kt#L9-L19

LouisCAD commented 6 years ago

The SuspenLazy class allows more than just usage for Room: https://github.com/LouisCAD/Splitties/blob/4b444d0e9ea87b26e3af236edb4b68545ce128fb/sample/src/main/java/com/louiscad/splittiessample/extensions/coroutines/SuspendLazy.kt#L7-L15

Here's how it can be used for Room: https://github.com/LouisCAD/Splitties/blob/4b444d0e9ea87b26e3af236edb4b68545ce128fb/sample/src/main/java/com/louiscad/splittiessample/extensions/coroutines/SuspendLazyRoom.kt#L8-L11

it can also be used for SharedPreferences: https://github.com/LouisCAD/Splitties/blob/4b444d0e9ea87b26e3af236edb4b68545ce128fb/sample/src/main/java/com/louiscad/splittiessample/prefs/GamePreferences.kt#L23-L24