Read data changes

Health data in Samsung Health can be changed or deleted. If you need to get data changes for a specific data type, use:

  • HealthDataStore.readChanges()

If sleep data is changed in Samsung Health, the readChanges() gives a changed data result. The result’s changed item includes a changed time, a change type with ChangeType.UPSERT and the updated data point. You can retrieve deleted sleep data using ChangeType.DELETE, it includes the ID of the deleted data record.

To read sleep data change, see the following example.

// Read sleep data changes since the last sync time
suspend fun getChangedSleep(lastSyncTime: Instant, endTime: Instant) {
    val healthDataStore = HealthDataService.getStore(applicationContext)
    val changeRequest = DataTypes.SLEEP.changedDataRequestBuilder
        .setChangeTimeFilter(InstantTimeFilter.of(lastSyncTime, endTime))
        .build()

    val changes = healthDataStore.readChanges(changeRequest).dataList
    changes.forEach { change ->
        if (change.changeType == ChangeType.DELETE) {
            val deletedDataUid = change.deleteDataUid
        } else if (change.changeType == ChangeType.UPSERT) {
            val upsertDataPoint = change.upsertDataPoint
        }
    }
}