Я написал небольшую вспомогательную библиотеку для доступа к общим значениям предпочтений в Kotlin Andorid. Это моя первая библиотека, и я впервые использую Kotlin.
Рад за любые отзывы:)
Доступно на Github: https://github.com/nastylion/Pref
implementation 'com.github.nastylion:Pref:0.0.5'
Эта библиотека обеспечивает легкий доступ к Shared Preferences на Android.
Чтение и запись асинхронные , выполняемые сопрограммами Kotlin .
Функция расширения обеспечивает связь с LiveData .
Все сделано в одной строке кода.
//string defines the key where the value is stored in the shared preferences
//false = default value & defines the type
val booleanValue = "sharedPreferenceKey".asPref(false)
//read
booleanValue.get()
//write
booleanValue.set(true)
booleanValue += true
Пример использования Shared Preference в качестве LiveData и двухсторонней привязки данных Android:
class MyViewModel: ViewModel() {
//Holds a MutableLiveData<Boolean> that is set as soon as the shared pref is read on a workerthread
val switchValue = "switch".asPref(false).asLiveData()
}
//using Two-Way Binding your UI stores changes automatically in shared preferences
<androidx.appcompat.widget.SwitchCompat
android:id="@+id/switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="@={viewModel.switchValue}"/>