本文正如标题所说的用rxjava实现数据的三级缓存分别为内存,磁盘,网络,刚好最近在看AndroID源码设计模式解析与实战(受里面的ImageLoader的设计启发)。
我把代码放到了我的hot项目中,github地址
源码下载地址:Rxjava_jb51.rar
1.使用concat()和first()的 *** 作符。
2.使用BehaviorSubject。
先说BehaviorSubject的实现方法,废话不多说直接上代码,
/** * Created by wukewei on 16/6/20. */public class BehaviorSubjectFragment extends BaseFragment { public static BehaviorSubjectFragment newInstance() { BehaviorSubjectFragment fragment = new BehaviorSubjectFragment(); return fragment; } String diskData = null; String networkData = "从服务器获取的数据"; BehaviorSubject<String> cache; VIEw mVIEw; @Nullable @OverrIDe public VIEw onCreateVIEw(LayoutInflater inflater,@Nullable VIEwGroup container,@Nullable Bundle savedInstanceState) { mVIEw = inflater.inflate(R.layout.fragment_content,container,false); init(); return mVIEw; } private voID init() { mVIEw.findVIEwByID(R.ID.get).setonClickListener(new VIEw.OnClickListener() { @OverrIDe public voID onClick(VIEw v) { subscriptionData(new Observer<String>() { @OverrIDe public voID onCompleted() { } @OverrIDe public voID onError(Throwable e) { } @OverrIDe public voID onNext(String s) { Log.d("onNext",s); } }); } }); mVIEw.findVIEwByID(R.ID.memory).setonClickListener(new VIEw.OnClickListener() { @OverrIDe public voID onClick(VIEw v) { BehaviorSubjectFragment.this.cache = null; } }); mVIEw.findVIEwByID(R.ID.memory_disk).setonClickListener(new VIEw.OnClickListener() { @OverrIDe public voID onClick(VIEw v) { BehaviorSubjectFragment.this.cache = null; BehaviorSubjectFragment.this.diskData = null; } }); } private voID loadNewWork() { Observable<String> o = Observable.just(networkData) .doOnNext(new Action1<String>() { @OverrIDe public voID call(String s) { BehaviorSubjectFragment.this.diskData = s; Log.d("写入磁盘","写入磁盘"); } }); o.subscribe(new Action1<String>() { @OverrIDe public voID call(String s) { cache.onNext(s); } },new Action1<Throwable>() { @OverrIDe public voID call(Throwable throwable) { } }); } private Subscription subscriptionData(@NonNull Observer<String> observer) { if (cache == null) { cache = BehaviorSubject.create(); Observable.create(new Observable.OnSubscribe<String>() { @OverrIDe public voID call(Subscriber<? super String> subscriber) { String data = diskData; if (data == null) { Log.d("来自网络","来自网络"); loadNewWork(); } else { Log.d("来自磁盘","来自磁盘"); subscriber.onNext(data); } } }) .subscribeOn(Schedulers.io()) .subscribe(cache); } else { Log.d("来自内存","来自内存"); } return cache.observeOn(AndroIDSchedulers.mainThread()).subscribe(observer); }}
其中最主要的是subscriptionData()这个方法,就是先判断 cache是否存在要是存在的话就返回内存中数据,再去判断磁盘数据是否存在,如果存在就返回,要是前面两种都不存在的时候,再去网络中获取数据。还有最重要的是当你从网络获取数据的时候要记得保存在内存中和保存在磁盘中,在磁盘获取数据的时候把它赋值给内存。
接下来就说说用concat()和first()的 *** 作符来实现,这是我在看AndroID源码设计模式解析与实战,作者在第一章的时候就介绍ImageLoader的设计。
在内存中存储的方式LruCache来实现的,磁盘存储的方式就是序列化存储。
1.定义一个接口:
/** * Created by wukewei on 16/6/19. */public interface ICache { <T> Observable<T> get(String key,Class<T> cls); <T> voID put(String key,T t);}
2.内存存储的实现
/** * Created by wukewei on 16/6/19. */public class MemoryCache implements ICache{ private LruCache<String,String> mCache; public MemoryCache() { final int maxMemory = (int) Runtime.getRuntime().maxMemory(); final int cacheSize = maxMemory / 8; mCache = new LruCache<String,String>(cacheSize) { @OverrIDe protected int sizeOf(String key,String value) { try { return value.getBytes("UTF-8").length; } catch (UnsupportedEnCodingException e) { e.printstacktrace(); return value.getBytes().length; } } }; } @OverrIDe public <T> Observable<T> get(final String key,final Class<T> cls) { return Observable.create(new Observable.OnSubscribe<T>() { @OverrIDe public voID call(Subscriber<? super T> subscriber) { String result = mCache.get(key); if (subscriber.isUnsubscribed()) { return; } if (TextUtils.isEmpty(result)) { subscriber.onNext(null); } else { T t = new Gson().fromJson(result,cls); subscriber.onNext(t); } subscriber.onCompleted(); } }); } @OverrIDe public <T> voID put(String key,T t) { if (null != t) { mCache.put(key,new Gson().toJson(t)); } } public voID clearMemory(String key) { mCache.remove(key); }}
3.磁盘存储的实现
/** * Created by wukewei on 16/6/19. */public class diskCache implements ICache{ private static final String name = ".db"; public static long OTHER_CACHE_TIME = 10 * 60 * 1000; public static long WIFI_CACHE_TIME = 30 * 60 * 1000; file fileDir; public diskCache() { fileDir = CacheLoader.getApplication().getCacheDir(); } @OverrIDe public <T> Observable<T> get(final String key,final Class<T> cls) { return Observable.create(new Observable.OnSubscribe<T>() { @OverrIDe public voID call(Subscriber<? super T> subscriber) { T t = (T) getdiskData1(key + name); if (subscriber.isUnsubscribed()) { return; } if (t == null) { subscriber.onNext(null); } else { subscriber.onNext(t); } subscriber.onCompleted(); } }) .subscribeOn(Schedulers.io()) .observeOn(AndroIDSchedulers.mainThread()); } @OverrIDe public <T> voID put(final String key,final T t) { Observable.create(new Observable.OnSubscribe<T>() { @OverrIDe public voID call(Subscriber<? super T> subscriber) { boolean isSuccess = isSave(key + name,t); if (!subscriber.isUnsubscribed() && isSuccess) { subscriber.onNext(t); subscriber.onCompleted(); } } }) .subscribeOn(Schedulers.io()) .observeOn(AndroIDSchedulers.mainThread()) .subscribe(); } /** * 保存数据 */ private <T> boolean isSave(String filename,T t) { file file = new file(fileDir,filename); ObjectOutputStream objectOut = null; boolean isSuccess = false; try { fileOutputStream out = new fileOutputStream(file); objectOut = new ObjectOutputStream(out); objectOut.writeObject(t); objectOut.flush(); isSuccess=true; } catch (IOException e) { Log.e("写入缓存错误",e.getMessage()); } catch (Exception e) { Log.e("写入缓存错误",e.getMessage()); } finally { closeSilently(objectOut); } return isSuccess; } /** * 获取保存的数据 */ private Object getdiskData1(String filename) { file file = new file(fileDir,filename); if (isCacheDataFailure(file)) { return null; } if (!file.exists()) { return null; } Object o = null; ObjectinputStream read = null; try { read = new ObjectinputStream(new fileinputStream(file)); o = read.readobject(); } catch (StreamCorruptedException e) { Log.e("读取错误",e.getMessage()); } catch (IOException e) { Log.e("读取错误",e.getMessage()); } catch (ClassNotFoundException e) { Log.e("错误",e.getMessage()); } finally { closeSilently(read); } return o; } private voID closeSilently(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (Exception ignored) { } } } /** * 判断缓存是否已经失效 */ private boolean isCacheDataFailure(file datafile) { if (!datafile.exists()) { return false; } long existTime = System.currentTimeMillis() - datafile.lastModifIEd(); boolean failure = false; if (NetWorkUtil.getNetworkType(CacheLoader.getApplication()) == NetWorkUtil.NETTYPE_WIFI) { failure = existTime > WIFI_CACHE_TIME ? true : false; } else { failure = existTime > OTHER_CACHE_TIME ? true : false; } return failure; } public voID cleardisk(String key) { file file = new file(fileDir,key + name); if (file.exists()) file.delete(); }}
isCacheDataFailure()方式中就是判断当前的数据是否失效,我是根据当前的网络状况来分wifi状况和非wifi状况,wifi状态下数据过期时间比较短,其他状态过期时间比较长。
4.CacheLoader的设计
/** * Created by wukewei on 16/6/19. */public class CacheLoader { private static Application application; public static Application getApplication() { return application; } private ICache mMemoryCache,mdiskCache; private CacheLoader() { mMemoryCache = new MemoryCache(); mdiskCache = new diskCache(); } private static CacheLoader loader; public static CacheLoader getInstance(Context context) { application = (Application) context.getApplicationContext(); if (loader == null) { synchronized (CacheLoader.class) { if (loader == null) { loader = new CacheLoader(); } } } return loader; } public <T> Observable<T> asDataObservable(String key,Class<T> cls,NetworkCache<T> networkCache) { Observable observable = Observable.concat( memory(key,cls),disk(key,network(key,cls,networkCache)) .first(new Func1<T,Boolean>() { @OverrIDe public Boolean call(T t) { return t != null; } }); return observable; } private <T> Observable<T> memory(String key,Class<T> cls) { return mMemoryCache.get(key,cls).doOnNext(new Action1<T>() { @OverrIDe public voID call(T t) { if (null != t) { Log.d("我是来自内存","我是来自内存"); } } }); } private <T> Observable<T> disk(final String key,Class<T> cls) { return mdiskCache.get(key,cls) .doOnNext(new Action1<T>() { @OverrIDe public voID call(T t) { if (null != t) { Log.d("我是来自磁盘","我是来自磁盘"); mMemoryCache.put(key,t); } } }); } private <T> Observable<T> network(final String key,NetworkCache<T> networkCache) { return networkCache.get(key,cls) .doOnNext(new Action1<T>() { @OverrIDe public voID call(T t) { if (null != t) { Log.d("我是来自网络","我是来自网络"); mdiskCache.put(key,t); mMemoryCache.put(key,t); } } }); } public voID clearMemory(String key) { ((MemoryCache)mMemoryCache).clearMemory(key); } public voID clearMemorydisk(String key) { ((MemoryCache)mMemoryCache).clearMemory(key); ((diskCache)mdiskCache).cleardisk(key); }}
5.网络获取的NetworkCache:
/** * Created by wukewei on 16/6/19. */public abstract class NetworkCache<T> { public abstract Observable<T> get(String key,final Class<T> cls);}
6.接下来看怎么使用
/** * Created by wukewei on 16/5/30. */public class ItemPresenter extends BasePresenter<ItemContract.VIEw> implements ItemContract.Presenter { private static final String key = "new_List"; protected int pn = 1; protected voID replacePn() { pn = 1; } private boolean isRefresh() { return pn == 1; } private NetworkCache<ListPopular> networkCache; public ItemPresenter(Activity activity,ItemContract.VIEw vIEw) { super(activity,vIEw); } @OverrIDe public voID getListData(String type) { if (isRefresh()) mVIEw.showLoading(); networkCache = new NetworkCache<ListPopular>() { @OverrIDe public Observable<ListPopular> get(String key,Class<ListPopular> cls) { return mHotAPI.getPopular(ItemPresenter.this.pn,Constants.PAGE_SIZE,type) .compose(SchedulersCompat.applyIoSchedulers()) .compose(RxResultHelper.handleResult()) .flatMap(populars -> { ListPopular popular = new ListPopular(populars); return Observable.just(popular); }); } }; Subscription subscription = CacheLoader.getInstance(mActivity) .asDataObservable(key + type + ItemPresenter.this.pn,ListPopular.class,networkCache) .map(ListPopular -> ListPopular.data) .subscribe(populars -> { mVIEw.showContent(); if (isRefresh()) { if (populars.size() == 0) mVIEw.showNotdata(); mVIEw.addRefreshData(populars); } else { mVIEw.addLoadMoreData(populars); } },throwable -> { if (isRefresh()) mVIEw.showError(ErrorHanding.handleError(throwable)); handleError(throwable); }); addSubscrebe(subscription); }}
一定要给个key,我是根据key来获取数据的,还要就是给个类型。
但是这个我设计的这个缓存还是不是很理想,接来下想要实现的就是在传入的时候类的class都不用给明,要是有好的实现的方式,欢迎告诉我。
总结以上是内存溢出为你收集整理的Android中Rxjava实现三级缓存的两种方式全部内容,希望文章能够帮你解决Android中Rxjava实现三级缓存的两种方式所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)