Guest User

Untitled

a guest
Apr 25th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. class AdapterStateRepository {
  2. private val keyGenerator = AtomicInteger()
  3. private val memoryCache = object : LruCache<Int, ByteArray>(MEMORY_CACHE_COUNT) {
  4. override fun entryRemoved(evicted: Boolean, key: Int?, oldValue: ByteArray?, newValue: ByteArray?) {
  5. if (evicted && oldValue != null && key != null) {
  6. writeToDiskCache(key, oldValue)
  7. }
  8. }
  9. }
  10.  
  11. private val cacheDirectory by lazy {
  12. File(TradeMeApp.getContext().cacheDir, DISK_CACHE_PREFIX).apply {
  13. delete()
  14. mkdir()
  15. }
  16. }
  17.  
  18. private fun writeToDiskCache(key: Int, oldValue: ByteArray) {
  19. File(cacheDirectory, key.toString()).writeBytes(oldValue)
  20. }
  21.  
  22. private fun getFromDiskCache(key: Int): ByteArray? = with(File(cacheDirectory, key.toString())) {
  23. return when {
  24. exists() && canRead() -> {
  25. val result = readBytes()
  26. delete()
  27. result
  28. }
  29. else -> null
  30. }
  31. }
  32.  
  33. fun put(bundle: Bundle): Int {
  34. val key = keyGenerator.getAndIncrement()
  35. with(Parcel.obtain()) {
  36. writeBundle(bundle)
  37. memoryCache.put(key, marshall())
  38. recycle()
  39. }
  40. return key
  41. }
  42.  
  43. fun get(key: Int, classLoader: ClassLoader): Bundle? {
  44. val data = memoryCache[key] ?: getFromDiskCache(key) ?: return null
  45. memoryCache.remove(key)
  46. with(Parcel.obtain()) {
  47. unmarshall(data, 0, data.size)
  48. setDataPosition(0)
  49. val bundle = readBundle(classLoader)
  50. recycle()
  51. return bundle
  52. }
  53. }
  54.  
  55. fun trimMemory(level: Int) {
  56. if (level >= ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL) {
  57. memoryCache.evictAll()
  58. }
  59. }
  60. }
Add Comment
Please, Sign In to add comment