Skip to content

@Refrigerate annotation

crypticminds edited this page Feb 7, 2020 · 1 revision

@Refrigerate annotation can be used on a method to cache the output of the method against the inputs of the method. For example, consider the following function :

   fun add(val a : Int , val b : Int) : Int {
       return a+b
   }

Annotating it with @Refrigerate will cache the returned value of this method for every value of a and b. So, if you call the method with a = 2 and b = 4, the cache will keep 2 and 4 as the key of the cache and 6 as the value so that the next time the function is called with the same inputs the value will be returned from the cache itself without invoking the method.

This is very useful for methods that make network calls to download some data.

Parameters

  • timeToLive (Int) -> An optional value that will determine how long the cached result from a method will stay "fresh". If the value expires, the next time the function is called with the same inputs it will be automatically refreshed and updated in the cache. This is useful if some data is expected to over a period of time.
  • keys (String[]) -> DEPRECATED Use @CacheKey annotation instead.
  • operation (String) -> A unique value for the method on which the annotation is applied.

Usage

  • Annotate a method with @Refrigerate

    class ClassWithMethods {
    
    @Refrigerate(operation = "customOperation")
    fun downloadSomethingFromInternet(@CacheKey val key : String , val someOtherVariable : String) : String {
     // method logic
     }
    }
    
  • The annotation will generate a new class that will wrap the original method with caching logic. Use the generated class and method instead of the original one. The generated class is -> com.arcane.generated.GeneratedCacheLayer and the generated method will have the same name as the original method but with two extra parameters. The first parameter is the object of the class which contains the annotated method and the second is the callback that will be used to pass the cached data from the background thread to the UI thread.

    import com.arcane.generated.GeneratedCacheLayer
    
    fun someMethodInMyActivity() {
    GeneratedCacheLayer.downloadSomethingFromInternet("key" , "otherVariable" , ClassWithMethods() , 
    object :OnOperationSuccessfulCallback<String?> {
              override fun onSuccess(output: String?, operation: String) {
                  //handle the output from the cache 
              })
    }
  • If the annotated method is static then the generated method will not require the object of the class and only the callback implementation needs to be passed to the generated method.

Clone this wiki locally