Skip to content

Commit

Permalink
Merge pull request #11 from Q42/bug/no-submit-timestamp-update-after-…
Browse files Browse the repository at this point in the history
…json-parsing-error

Bug: no update of submit interval after json parsing error
  • Loading branch information
Techwolf12 authored Sep 14, 2022
2 parents 3d16e03 + c303f7b commit cb35c14
Showing 1 changed file with 38 additions and 28 deletions.
66 changes: 38 additions & 28 deletions q42stats/src/main/java/com/q42/q42stats/library/Q42Stats.kt
Original file line number Diff line number Diff line change
Expand Up @@ -43,39 +43,49 @@ class Q42Stats(private val config: Q42StatsConfig) {

@WorkerThread
private fun runSync(context: Context) {
try {
val prefs = Q42StatsPrefs(context)
if (prefs.withinSubmitInterval(config.minimumSubmitIntervalSeconds * 1000L)) {
Q42StatsLogger.i(
TAG,
"Q42Stats were already sent in the last ${config.minimumSubmitIntervalSeconds} seconds."
withPrefs(context) { prefs ->
try {
if (prefs.withinSubmitInterval(config.minimumSubmitIntervalSeconds * 1000L)) {
Q42StatsLogger.i(
TAG,
"Q42Stats were already sent in the last ${config.minimumSubmitIntervalSeconds} seconds."
)
return@withPrefs
}
Q42StatsLogger.i(TAG, "Q42Stats: Start")

val currentMeasurement = collect(context)

val payload: Map<String, Any> = mapOf<String, Any?>(
"Stats Version" to "Android ${BuildConfig.LIB_BUILD_DATE}",
"currentMeasurement" to currentMeasurement,
"previousMeasurement" to prefs.previousMeasurement,
).filterValueNotNull()
val responseBody = HttpService.sendStatsSync(
config,
payload.toQ42StatsApiFormat(),
prefs.lastBatchId
)
return
}
Q42StatsLogger.i(TAG, "Q42Stats: Start")

val currentMeasurement = collect(context)

val payload: Map<String, Any> = mapOf<String, Any?>(
"Stats Version" to "Android ${BuildConfig.LIB_BUILD_DATE}",
"currentMeasurement" to currentMeasurement,
"previousMeasurement" to prefs.previousMeasurement,
).filterValueNotNull()
val responseBody = HttpService.sendStatsSync(
config,
payload.toQ42StatsApiFormat(),
prefs.lastBatchId
)
responseBody?.let {
val batchId = it.getString("batchId") // throws if not found
prefs.lastBatchId = batchId
prefs.previousMeasurement = currentMeasurement
prefs.updateSubmitTimestamp()
responseBody?.let {
val batchId = it.getString("batchId") // throws if not found
prefs.lastBatchId = batchId
prefs.previousMeasurement = currentMeasurement
}
} catch (e: Throwable) {
handleException(e)
} finally {
prefs.updateSubmitTimestamp() // make sure to always update the submit timestamp
Q42StatsLogger.i(TAG, "Q42Stats: Exit")
}
}
}

private fun withPrefs(context: Context, action: (prefs: Q42StatsPrefs) -> Unit) {
try {
val prefs = Q42StatsPrefs(context)
action(prefs)
} catch (e: Throwable) {
handleException(e)
} finally {
Q42StatsLogger.i(TAG, "Q42Stats: Exit")
}
}
Expand Down

0 comments on commit cb35c14

Please sign in to comment.