欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android中Rxjava实现三级缓存的两种方式

程序员文章站 2023-01-21 10:15:41
本文正如标题所说的用rxjava实现数据的三级缓存分别为内存,磁盘,网络,刚好最近在看android源码设计模式解析与实战(受里面的imageloader的设计启发)。...

本文正如标题所说的用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, cls),
        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, class<t> cls
      , 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都不用给明,要是有好的实现的方式,欢迎告诉我。