Skip to content

Instantly share code, notes, and snippets.

View adesamp's full-sized avatar
🏠

Ade Dyas adesamp

🏠
View GitHub Profile
// 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() {
@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)
}
// 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) =
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
)
class MainActivity : AppCompatActivity() {
private lateinit var bmiBrain: BmiBrain
// initialize class
bmiBrain = BmiBrain(this)
// load value
binding.apply {
lifecycleScope.launch {
val name = async { bmiBrain.getName() }
implementation "androidx.datastore:datastore-preferences:1.0.0-alpha08"
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) }
class MainActivity : AppCompatActivity() {
// initialize view model, in this case using koin extension
private val viewModel: MainViewModel by viewModel()
// observe value
viewModel.name.observe(this, ::setName)
private fun setName(name: String?) = binding.edtName.setText(name)
// fetch data on the first time / activtity created
@adesamp
adesamp / jobtest.kt
Last active July 7, 2021 11:45
JobTest
@Test
fun `Join Test`() {
runBlocking {
val job : Job = launch { println(Thread.currentThread().name) }
job.join()
}
}
@Test
fun `JoinAll Test`() {