Skip to content

Instantly share code, notes, and snippets.

View adesamp's full-sized avatar
🏠

Ade Dyas adesamp

🏠
View GitHub Profile
class MainViewModel(private val dataStore: DataStore<Preferences>) : ViewModel() {
private val _name = MutableLiveData<String>()
val name: LiveData<String>
get() = _name
fun fetch() {
viewModelScope.launch {
dataStore.data
.catch { _name.postValue(it.message) }
implementation "androidx.datastore:datastore-preferences:1.0.0-alpha08"
class MainActivity : AppCompatActivity() {
private lateinit var bmiBrain: BmiBrain
// initialize class
bmiBrain = BmiBrain(this)
// load value
binding.apply {
lifecycleScope.launch {
val name = async { bmiBrain.getName() }
// inisialisasi
companion object {
private val NAME_KEY = stringPreferencesKey("NAME_KEY")
}
private val Context._dataStore: DataStore<Preferences> by preferencesDataStore(
name = "sampingan_data_store",
produceMigrations = ::sharedPreferencesMigration
)
fun <T> DataStore<Preferences>.getValueFlow(
key: Preferences.Key<T>,
defaultValue: T,
): Flow<T> {
return this.data
.catch { exception ->
if (exception is IOException) {
emit(emptyPreferences())
} else {
throw exception
// inisialisasi
companion object {
private val NAME_KEY = stringPreferencesKey("NAME_KEY")
}
private val Context._dataStore: DataStore<Preferences> by preferencesDataStore(
name = "sampingan_data_store",
produceMigrations = ::sharedPreferencesMigration
)
private fun sharedPreferencesMigration(context: Context) =
@adesamp
adesamp / SharedPreferencesActivity.kt
Last active March 29, 2021 03:07
DataStore sync same like this, no need changes
class MainActivity : AppCompatActivity() {
private lateinit var bmiBrain: BmiBrain
// initialize class
bmiBrain = BmiBrain(this)
// load value
binding.apply {
edtName.setText(bmiBrain.name)
}
// init SharedPreferences
companion object {
private const val NAME_KEY = "NAME_KEY"
}
private val preferences = activity.getSharedPreferences("pref_name", Context.MODE_PRIVATE)
private val editor = preferences.edit()
var name: String
// get/load value
get() {