There Is A Delay When Saving Data Into Room Database

I’m trying to create a stop watch application. Everything works fine at first. The stop watch goes up from the milliseconds, to the seconds, to the minutes just fine. There are two timers, one of the current time and one for the lap time. The problem comes when trying to add laps.

The laps are saved into Room so they’ll stay there on recomposition. The current time and the lap time are retrieved and placed into an item into a lazy column. However, the first lap is empty and the time is around four seconds to early. For example, if you created a lap at seven seconds it would actually say three seconds.

Here is the Main Activity. There is an instance of the viewmodel and database at the top. There are two sets of three variables representing the time. One set is for the current time, one set is for the lap time. The timers are triggered by booleans that start a launched effect. There is a button to start/stop, reset, and lap the timer. Underneath that is a lazy column that displays the laps.

class MainActivity : ComponentActivity() {

    private val stopWatchDatabase by lazy {
        Room.databaseBuilder(
            applicationContext,
            StopWatchDatabase::class.java,
            name = "object.database"
        ).build()
    }
    private val viewModel by viewModels<StopWatchViewModel> (
        factoryProducer =  {
            object: ViewModelProvider.Factory{
                override fun <T: ViewModel> create(modelClass: Class<T>): T{
                    return StopWatchViewModel((stopWatchDatabase)) as T
                }
            }
        }
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {

            // Time
            var milliseconds by remember { mutableIntStateOf(0) }
            var seconds by remember { mutableIntStateOf(0) }
            var minutes by remember { mutableIntStateOf(0) }

            // Lap Time
            var lapMilliseconds by remember { mutableIntStateOf(0) }
            var lapSeconds by remember { mutableIntStateOf(0) }
            var lapMinutes by remember { mutableIntStateOf(0) }

            // Time Display
            var overallTime by remember { mutableStateOf("") }
            var lapTime by remember { mutableStateOf("") }

            // Timer Active States
            var isTimerActive by remember { mutableStateOf(false) }
            var isLapTimerActive by remember { mutableStateOf(false) }

            // Lap List
            var laps by remember { mutableStateOf(listOf<Lap>()) }

            // Instance Of Lap Entity
            val newLap = Lap(
                lapNumber = laps.size + 1,
                overallTime = overallTime,
                lapTime = lapTime
            )

            // Function To Retrieve Lap List
            viewModel.retrieveAllLaps().observe(LocalLifecycleOwner.current) {
                 laps = it
            }

            // Start Timer Launched Effect
            LaunchedEffect(isTimerActive) {
                while (isTimerActive && milliseconds < 100) {
                    delay(1)
                    milliseconds++
                    while (milliseconds == 100) {
                        seconds += 1
                        milliseconds = 0
                        while (seconds == 60) {
                            minutes += 1
                            seconds = 0
                            milliseconds = 0
                        }
                    }
                }
            }

            // Start Lap Timer Launched Effect
            LaunchedEffect(isTimerActive && isLapTimerActive) {
                while (isTimerActive && isLapTimerActive && lapMilliseconds < 100) {
                    delay(1)
                    lapMilliseconds++
                    while (lapMilliseconds == 100) {
                        lapSeconds += 1
                        lapMilliseconds = 0
                        while (lapSeconds == 60) {
                            lapMinutes += 1
                            lapSeconds = 0
                            lapMilliseconds = 0
                        }
                    }
                }
            }

            // App Layout
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center,
                modifier = Modifier
                    .fillMaxSize()
            ) {
                // Time Display
                Text(
                    text = "%02d:%02d:%02d".format(minutes, seconds, milliseconds),
                    fontSize = 50.sp
                    )
                if (isLapTimerActive) {

                    // Lap Time Display
                     Text(
                     text = "%02d:%02d:%02d".format(lapMinutes, lapSeconds, lapMilliseconds),)
                }

                // Button To Start Timer
                Button(onClick = { isTimerActive = !isTimerActive }) {
                Text(text = "Start")
                }

                // Button To Reset Timer
                Button(onClick = {
                    CoroutineScope(Dispatchers.IO).launch {
                        isTimerActive = false
                        isLapTimerActive = false
                        viewModel.deleteAllLaps()
                        delay(1)
                        milliseconds = 0
                        seconds = 0
                        minutes = 0
                        lapMilliseconds = 0
                        lapSeconds = 0
                        lapMinutes = 0
                        overallTime = ""
                        lapTime = ""
                    }}) {
                    Text(text = "Reset")
                }

                 // Button To Lap Timer
                Button(onClick = {
                    overallTime = "%02d:%02d:%02d".format(minutes, seconds, milliseconds)
                    lapTime = "%02d:%02d:%02d".format(lapMinutes, lapSeconds, lapMilliseconds)
                    viewModel.insertLap(newLap)
                    lapMilliseconds = 0
                    lapSeconds = 0
                    lapMinutes = 0
                    isLapTimerActive = true
                 }) {
                    Text(text = "Lap")
                }

                // Lap List
                LazyColumn(
                    verticalArrangement = Arrangement.spacedBy(30.dp)
                ) {
                    items(laps) { lap ->
                        Row(
                        horizontalArrangement = Arrangement.spacedBy(30.dp)
                    ) {
                        Text(text = lap.lapNumber.toString())
                        Text(text = lap.lapTime)
                        Text(text = lap.overallTime)
                       }
                    }
                }
            }
        }
    }
}

Here is Lap Entity

@Entity
data class Lap(

    val lapNumber: Int?,
    val overallTime: String,
    var lapTime: String,

    @PrimaryKey(autoGenerate = true)
    val id: Int = 0
)

Here is the Stopwatch Dao

@Dao
interface StopWatchDao {
    @Upsert
    suspend fun insertLap(lap: Lap)

    @Query("DELETE FROM Lap")
    suspend fun deleteAllLaps()

    @Query("SELECT * FROM Lap")
    fun retrieveAllLaps(): Flow<List<Lap>>
}

Here is the Stopwatch Database

@Database(
    entities = [Lap::class],
    version = 1
)
abstract class StopWatchDatabase: RoomDatabase() {
    abstract val stopWatchDao: StopWatchDao
}

And finally the Stopwatch ViewModel

class StopWatchViewModel(private val stopWatchDatabase: StopWatchDatabase): ViewModel() {

     fun insertLap(lap: Lap){
        viewModelScope.launch {
        stopWatchDatabase.stopWatchDao.insertLap(lap)
        }
    }

    fun deleteAllLaps(){
        viewModelScope.launch {
        stopWatchDatabase.stopWatchDao.deleteAllLaps()
        }
    }

    fun retrieveAllLaps() = stopWatchDatabase.stopWatchDao.retrieveAllLaps().asLiveData(viewModelScope.coroutineContext)
}

I tried placing the insertLap function into coroutine and adding a delay but that didn’t work.

But away the problem is that the first lap in the lazy column is empty except for the lap number and the time on the rest is four seconds too early.

Thanks for your time reading my question.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật