Skip to content

ehsannarmani/EasyShared

Repository files navigation

EasyShared

A Library For Using Shared Preferences Easier

Usage:

    var token:String by savable("auth_token")
    var age:Int by savable() /* savable("age") */
    var loggedIn:Boolean by savable() /* savable("loggedIn") */

    var phone by savableInt()
    var name by savableString()
    var timestamp by savableLong()

Note: you can pass variable key to save in shared preferences, but if you don't, it will save in variable name, for exmaple:

    var username:String by savable()

Here, that username will save in 'username' key, and:

    var username:String by savable("name")

Here, that username will save in 'user' key

Updating

For update and re-save variable value in shared prefrences, just update that savable value, that's it! , for example:

  var token:String by savable("auth_token")

  token = "xxxxx"
  var userId by savableInt()

  userId = 43

No need to do anything else.

Saving Objects & ListOf Them

  data class Person(val id:Int,val name:String)

  val persons:List<Person> by savable(defauleValue = emptyList())

Final Sample In Jetpack Compose:

  var token:String by savable("auth_token")
  var user:User by savable(defaultValue = User(id = -1,name = "empty user"))

  Button(onClick = {
      token = UUID.randomUUID().toString()
      user = User(id = 342, name = "Iran")
  }) {
     Text(text = "Set")
  }
  Button(onClick = {
      println(user.name)
      Toast.makeText(context, token, Toast.LENGTH_SHORT).show()
  }) {
      Text(text = "Get")
  }

Dependency

Add the JitPack repository to your build file

Add Jitpack Maven in your settings.gradle file:

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

Kotlin DSL(build.gradle.kts):

    repositories {
        ...
        maven("https://jitpack.io")
    }   

Add the dependency

Groovy:

dependencies {
      implementation 'com.github.ehsannarmani:EasyShared:latest_version'
}

Kotlin DSL (build.gradle.kts):

dependencies {
    implementation("com.github.ehsannarmani:EasyShared:latest_version")
}