A Kotlin library for reactive and boilerplate-free SharedPreferences in Android

Overview

Bintray Min API Android Arsenal License Methods Count

KPreferences

A Kotlin library for reactive and boilerplate-free Shared Preferences in Android. With KPreferences you can use Kotlin's marvelous delegate concept to easily use Android's Shared Preferences. Features:

  • Boilerplate-free: Use SharedPreferences properties with one line and without edit, apply or ... boilerplate codes
  • Reactive: Use observables to listen for SharedPreferences changes without any memory leak
  • Custom types: You are not limited to a set of limited types that can be saved to the SharedPreferences .

If you have any issues or need more features, you can submit an issue in the issue tracker or make a pull request.

Demo

Importing

Add this line to your module's build.gradle file:

dependencies {
    compile 'com.mohamadamin.kpreferences:kpreferences:0.1'
}

Usage

First you need to initialize KPreferenceManager in your application class. You can also provide name of the SharedPreference and mode for the operating mode but it's not needed (defaults to "default" for file name and Context.MODE_PRIVATE for mood):

override fun onCreate() {
    super.onCreate()
    KPreferenceManager.initialize(this)
}

Use SharedPreferences in your project with only one line:

val intPreference: Int by Preference(-1, "IntPreference")

it creates a SharedPreferences property with IntPreference name and -1 as its default value.

Then the intPreference property is automatically saved when you change the intPreference property and is directly retrieved from SharedPreferences when you want to access its value:

// the age value is directly retrieved from SharedPreferences property named "IntPreference"
someClass.age = intPreference
// automatically is saved in shared preferences with no need to edit or ...
intPreference = 21

Reactive Preferences

KPreferences also provides Observable Preferences that lets you observe changes to a single preference. It uses SharedPreferences's registerOnSharedPreferenceChangeListener method.

But unlike that method that requires you to observe changes on all fields ObservablePreference lets you only listen to the changes that you need:

// Composite destroyer to destroy all observables at once to avoid memory leaks
val destroyers = CompositeDestroyer()
var toolbarTitle: Int by ObservablePreference(
            "ToolbarTitle", // SharedPreferences key
            "Title", // SharedPreferences default value
            subscriber = object: Subscriber<Int> { // observable for possible changes
                override val subscriber: (Int) -> Unit
                    get() = {
	                    // changing toolbar title when the preference is changed
                        setToolbarTitle("$it") 
                    }
                override fun setDestroyListener(callback: () -> Unit) {
                    // call this callback later to unregister the listener and avoid memory leaks
                    destroyers.add(callback) 
                }
            }
    )

but you need to destroy the destroyable callback in your onDestroy to avoid possible memory leaks. The CompositeDestroyer is a helper class to destroy all callbacks at once:

override fun onDestroy() {
    super.onDestroy()
    destroyers.invoke()
}

Custom Types

You can use the adapter abstraction to store and retrieve values of an arbitrary type.

As you see below you should override decode and encode functions of the Adapter<T> class to create an adapter for the variable of type T and save/restore it in SharedPreferences. There's an example of an adapter which uses Gson to serialize/deserialize the custom type in the demo app.

/**
 * @author MohamadAmin Mohamadi ([email protected]) on 3/16/17.
 * Converter for storing and retrieving objects of type [T] in [android.content.SharedPreferences]
 */
interface Adapter<T> {

    /**
     * Decode the string retrieved from [android.content.SharedPreferences] to an object of type [T]
     * @param result the string retrieved from {@link SharedPreferences}
     * @return the decoded object of type [T]
     */
    fun decode(result: String): T?

    /**
     * Encode an object of type [T] to a string that can be saved in [android.content.SharedPreferences]
     * @param value the object of type [T] that wants to be saved in [android.content.SharedPreferences]
     * @return the encoded string from the input #value that can be saved in [android.content.SharedPreferences]
     */
    fun encode(value: T): String

}

Demo

You can see a full demo of the library in the app module.

License

Copyright 2017 Mohamad Amin Mohamadi

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
You might also like...
Clean Code and Reactive Programming PlayGround for Bangkit 2021

Clean Code and Reactive Programming PlayGround for Bangkit 2021 Hello! This repo contains the IntelliJ project that I use to present my talk, "Clean A

Android-Boilerplate - Base project for android development with new technology

Android-Boilerplate Base project for android development with new technology, in

Ivy FRP is a Functional Reactive Programming framework for declarative-style programming for Android

FRP (Functional Reactive Programming) framework for declarative-style programming for Andorid. :rocket: (compatible with Jetpack Compose)

A fork of our clean architecture boilerplate, this time using the Android Architecture Components

Android Clean Architecture Components Boilerplate Note: This is a fork of our original Clean Architecture Boilerplate, except in this repo we have swi

An android boilerplate project using clean architecture

Android Clean Architecture Boilerplate Welcome 👋 We hope this boilerplate is not only helpful to other developers, but also that it helps to educate

A fork of our clean architecture boilerplate using the Model-View-Intent pattern

Android Clean Architecture MVI Boilerplate Note: This is a fork of our original Clean Architecture Boilerplate, except in this repo we have switched o

Free and Open Source monster taming video game. Inspired by traditional RPGs like Pokémon, Final Fantasy and Golden Sun.
Free and Open Source monster taming video game. Inspired by traditional RPGs like Pokémon, Final Fantasy and Golden Sun.

Welcome Help Wanted: I cannot finish this on my own. If you are willing to help, let me know. GuardianMonsters is a Free and Open Source monster tamin

Udacity Free course: Developing Android Apps with Kotlin
Udacity Free course: Developing Android Apps with Kotlin

Room - SleepQualityTracker app This is the toy app for Lesson 6 of the Android App Development in Kotlin course on Udacity. SleepQualityTracker The Sl

🏗️ Kotlin implementation of Point-Free's composable architecture

🧩 Komposable Architecture Kotlin implementation of Point-Free's The Composable Architecture 🚧 Project Status We've been using Komposable Architectur

Owner
Mohamad Amin Mohamadi
Tryna reach the infinite
Mohamad Amin Mohamadi
[Android Library] A SharedPreferences helper library to save and fetch the values easily.

Preference Helper A SharedPreferences helper library to save and fetch the values easily. Featured in Use in your project Add this to your module's bu

Naveen T P 13 Apr 4, 2020
Easy lightweight SharedPreferences library for Android in Kotlin using delegated properties

Easy lightweight SharedPreferences library for Android in Kotlin using delegated properties Idea Delegated properties in Kotlin allow you to execute a

null 24 Oct 3, 2022
Kotpref - Android SharedPreferences delegation library for Kotlin

Kotpref Android SharedPreference delegation for Kotlin. Install repositories { mavenCentral() } dependencies { // core implementation 'co

Takao Chiba 683 Nov 26, 2022
Android Library to make SharedPreferences usage easier.

KotlinPreferences Kotlin Android Library, that makes preference usage simple and fun. KotlinPreferences now have a brother. With KotlinPreferences, yo

Marcin Moskała 50 Nov 6, 2022
Adapter library for SharedPreferences

EasyPrefs Adapter library for SharedPreferences which reduces boilerplate needed to store simple data, but open enough to not interfere with your own

Kacper Wojciechowski 6 Nov 23, 2021
A Kotlin Android library for content provider queries with reactive streams and coroutines.

Pickpocket An Android library for content provider queries with reactive streams and coroutines. Calendar Contacts SMS MMS Files/Media Call Log Bookma

Chris Basinger 27 Nov 14, 2022
👋 A common toolkit (utils) ⚒️ built to help you further reduce Kotlin boilerplate code and improve development efficiency. Do you think 'kotlin-stdlib' or 'android-ktx' is not sweet enough? You need this! 🍭

Toolkit [ ?? Work in progress ⛏ ?? ??️ ?? ] Snapshot version: repositories { maven("https://s01.oss.sonatype.org/content/repositories/snapshots") }

凛 35 Jul 23, 2022
Android SharedPreferences Helper

PocketDB Android SharedPreferences Helper This is SharedPreferences Helper like a database noSql. Support AES encryption Latest Version Download depen

Muhammad Utsman 9 Jun 20, 2021
An Android template project (in Kotlin) with boilerplate and current patterns.

android-starter-v4 An Android template project (in Kotlin) with boilerplate and plumbing, exploring current architecture patterns. A bit too much for

Matthias Urhahn 14 Nov 4, 2022
Boilerplate code for implementing MVVM in Android using Jetpack libraries, coroutines, dependency injection and local persistance

MVVM Foundation This projects aims to speed up development of Android apps by providing a solid base to extend Libraries Jetpack Fragment Material3 :

Gabriel Gonzalez 2 Nov 10, 2022