In order to support synchronization of time using ...
# room
b
In order to support synchronization of time using NTP for time sensitive data, I've added a
Volatile
property to our
RoomDatabase
from where all update operations can request a "timestamp". But I was wondering if this is threadsafe in regards to using Room with suspending functions and transactions? Also not quite sure it actually has to be marked as
Volatile
as every access should produce a new
java.time.Clock
. Code follows in thread...
Example:
Copy code
abstract class AppDatabase : RoomDatabase() {

    abstract val chatRepository: ChatRepository
    abstract val taskRepository: TaskRepository
    abstract val userSampleRepository: UserRepository

    companion object {
        private const val DB_NAME = "example_database"

        @Volatile
        internal var clock: Clock = Clock.systemDefaultZone()
            private set

        ...
        @JvmStatic
        fun withClock(clock: Clock) {
            synchronized(this) {
                this.clock = clock
            }
        }
    }
}
When used:
Copy code
@Dao
abstract class TaskRepository
...
    private suspend fun updateAll(tasks: List<TaskEntity>) = updateAllInternal(
        tasks.map {
            TaskEntity.Builder()
                .copyOf(it)
                .withUpdatedAt(OffsetDateTime.now(AppDatabase.clock))
                .create()
        }
    )
...
}