Skip to content

Commit

Permalink
Add resource cache
Browse files Browse the repository at this point in the history
  • Loading branch information
kylecorry31 committed Mar 18, 2023
1 parent c0c7a7b commit c2e0665
Showing 1 changed file with 43 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.kylecorry.andromeda.core.system

import android.content.res.Resources
import android.os.Build
import java.util.*

class ResourceCache(private val resources: Resources) {

private var lastLocale = getLocale()
private val cache = mutableMapOf<Int, String>()
private val lock = Any()

fun getString(id: Int): String {
synchronized(lock) {
val currentLocale = getLocale()
if (lastLocale != currentLocale) {
cache.clear()
lastLocale = currentLocale
}

if (cache.containsKey(id)) {
return cache[id]!!
}
val string = resources.getString(id)
cache[id] = string
return string
}
}

fun getString(id: Int, vararg formatArgs: Any): String {
val raw = getString(id)
return String.format(lastLocale, raw, *formatArgs)
}

private fun getLocale(): Locale {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
resources.configuration.locales[0]
} else {
@Suppress("DEPRECATION")
resources.configuration.locale
}
}
}

0 comments on commit c2e0665

Please sign in to comment.