Splitties icon indicating copy to clipboard operation
Splitties copied to clipboard

Add suspend room db accessor

Open LouisCAD opened this issue 7 years ago • 4 comments

LouisCAD avatar Aug 24 '18 09:08 LouisCAD

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 avatar Aug 24 '18 11:08 LouisCAD

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

LouisCAD avatar Aug 24 '18 12:08 LouisCAD

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 avatar Nov 20 '18 23:11 LouisCAD

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

LouisCAD avatar Nov 25 '18 15:11 LouisCAD