Dart Documentationclean_sync.serverCache

Cache class

class Cache {
 Duration _timeOut;
 num _capacity;
 LinkedHashMap<dynamic, Entry> _entries = {};

 Cache(this._timeOut, this._capacity);

 _removeFirst(){
   _entries.remove(_entries.keys.first);
 }

 clear(){
   var toRemove = [];
   for(var k in _entries.keys){
     if ((new DateTime.now()).isAfter(_entries[k].expirationDate)) {
       toRemove.add(k);
     } else {
       break;
     }
   }
   toRemove.forEach((e){_entries.remove(e);});
   while(_entries.length > _capacity) {
     _removeFirst();
   }
 }

 put(key, val){
   var timeAdded = new DateTime.now();
   var expirationDate = timeAdded.add(_timeOut);
   _entries[key] = new Entry(val, timeAdded, expirationDate);
   clear();
 }


 Future putIfAbsent(key, val()){
   clear();
   if (_entries.containsKey(key)) {
     return new Future.delayed(new Duration(), () => _entries[key].value);
   } else {
       return new Future.sync(() => val())
         .then((value){
         put(key, value);
         return value;
     });
   }
 }

 Entry getEntry(key){
   clear();
   return _entries[key];
 }

 get(key){
   Entry res = getEntry(key);
   if (res == null) {
     return null;
   } else {
     return res.value;
   }
 }

}

Subclasses

DummyCache

Constructors

new Cache(Duration _timeOut, num _capacity) #

Creates a new Object instance.

Object instances have no meaningful state, and are only useful through their identity. An Object instance is equal to itself only.

docs inherited from Object
Cache(this._timeOut, this._capacity);

Methods

dynamic clear() #

clear(){
 var toRemove = [];
 for(var k in _entries.keys){
   if ((new DateTime.now()).isAfter(_entries[k].expirationDate)) {
     toRemove.add(k);
   } else {
     break;
   }
 }
 toRemove.forEach((e){_entries.remove(e);});
 while(_entries.length > _capacity) {
   _removeFirst();
 }
}

dynamic get(key) #

get(key){
 Entry res = getEntry(key);
 if (res == null) {
   return null;
 } else {
   return res.value;
 }
}

Entry getEntry(key) #

Entry getEntry(key){
 clear();
 return _entries[key];
}

dynamic put(key, val) #

put(key, val){
 var timeAdded = new DateTime.now();
 var expirationDate = timeAdded.add(_timeOut);
 _entries[key] = new Entry(val, timeAdded, expirationDate);
 clear();
}

Future putIfAbsent(key, val()) #

Future putIfAbsent(key, val()){
 clear();
 if (_entries.containsKey(key)) {
   return new Future.delayed(new Duration(), () => _entries[key].value);
 } else {
     return new Future.sync(() => val())
       .then((value){
       put(key, value);
       return value;
   });
 }
}