-
Notifications
You must be signed in to change notification settings - Fork 0
/
RxCache.kt
76 lines (64 loc) · 1.91 KB
/
RxCache.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.fanhl.rxcache
import android.content.Context
import android.content.SharedPreferences
import com.google.gson.reflect.TypeToken
import io.reactivex.ObservableTransformer
/**
* desc:
* date: 2017/7/10
*
* @author fanhl
*/
object RxCache {
/** 已初始化过了 */
var inited = false
var provider: ICacheProvider? = null
/**
* This method should be called in Application.onCreate() only once.
*/
fun init(context: Context) {
checkInited()
provider = SharePreferenceCacheProvider(context)
}
/**
* This method should be called in Application.onCreate() only once.
*/
fun init(sharedPreferences: SharedPreferences) {
checkInited()
provider = SharePreferenceCacheProvider(sharedPreferences)
}
inline fun <reified T> cache(
name: Any,
vararg conditions: Any
) = ObservableTransformer<T, T> { upStream ->
checkInit()
val key = arrayOf(name, *conditions).joinToString("-")
var currStream = upStream.map { CacheWrap(it) }
val cacheWrap: CacheWrap<T>? = provider!!.get(key, object : TypeToken<CacheWrap<T>>() {}.type)
cacheWrap?.let {
//以防doOnNext时进行重复缓存
it.type = CacheWrap.Type.FromCache
currStream = currStream.startWith(it)
}
currStream.doOnNext {
if (it.type != CacheWrap.Type.FromCache) {
provider!!.put(key, it)
}
}.map { it.data }
}
fun checkInit() {
if (provider == null) {
throw Exception("""Provider not init.
may be you forget call RxCache.init().
Remember call init() before cache().
Please call init() in YourApplication.""")
}
}
private fun checkInited() {
if (!inited) {
inited = true
} else {
throw Exception("""RxCache can only init once.""")
}
}
}