Skip to content

Commit

Permalink
Correction exception
Browse files Browse the repository at this point in the history
  • Loading branch information
diefferson committed Nov 11, 2018
1 parent e470292 commit 241b844
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 14 deletions.
2 changes: 1 addition & 1 deletion .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 7 additions & 13 deletions library/src/main/java/io/coroutines/cache/core/CoroutinesCache.kt
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ open class CoroutinesCache(private var context: Context): CoroutineScope{

fun getDataBase() = Room.databaseBuilder(context, LocalDatabase::class.java, context.packageName+CACHE_PREFIX).build().cacheDao()

inline fun <reified T:Any> asyncCache(noinline source: suspend ()->T, key: String, forceSource:Boolean): Deferred<T> {
inline fun <reified T:Any> asyncCache(noinline source: suspend ()->Deferred<T>, key: String, forceSource:Boolean): Deferred<T> {
return if (forceSource) {
getFromSource(source, key)
} else {
Expand All @@ -32,24 +32,19 @@ open class CoroutinesCache(private var context: Context): CoroutineScope{
}
}

fun <T> getFromSource(source: suspend ()->T, key: String):Deferred<T>{
fun <T> getFromSource(source: suspend ()->Deferred<T>, key: String):Deferred<T>{
return async {
val response = source()
getDataBase().insert(Cache(key, Gson().toJson(response)))
response
val result = source().await()
getDataBase().insert(Cache(key, Gson().toJson(result)))
result
}
}

inline fun <reified T:Any> getFromCache(key: String): T? {
val resultDb = getDataBase().get(key)?.data
return if (resultDb != null) {
try {
val listType = object : TypeToken<T>() {}.type
Gson().fromJson(resultDb, listType) as T
}catch (e:StackOverflowError){
Gson().fromJson<T>(resultDb, T::class.java) as T
}

val listType = object : TypeToken<T>() {}.type
Gson().fromJson(resultDb, listType) as T
} else {
return null
}
Expand All @@ -59,4 +54,3 @@ open class CoroutinesCache(private var context: Context): CoroutineScope{
private const val CACHE_PREFIX = "cache"
}
}

0 comments on commit 241b844

Please sign in to comment.