Skip to content

Instantly share code, notes, and snippets.

View egorshustov's full-sized avatar

Egor Shustov egorshustov

View GitHub Profile
import android.content.SharedPreferences
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class DelegatedPreference<T>(
private val sharedPrefs: SharedPreferences,
private val key: String,
private val defValue: T
) : ReadWriteProperty<Any?, T> {
import android.content.SharedPreferences
import androidx.lifecycle.LiveData
class LivePreference<T>(
private val sharedPrefs: SharedPreferences,
private val key: String,
private val defValue: T
) : LiveData<T?>() {
private val preferenceChangeListener =
sealed class ResponseMessage {
class Success(val message: String?) : ResponseMessage()
class Error(val message: String?, val throwable: Throwable?) : ResponseMessage()
fun getErrorMessage(): String? {
return when (this) {
is Success -> {
null
}
is Error -> {
@egorshustov
egorshustov / Coroutines2.kt
Created January 10, 2019 05:30
Two ways to create async functions in ViewModel class
class LoginViewModel(context: Application) : AndroidViewModel(context) {
...
fun isUserExists(id: Int) = viewModelScope.async {
usersRepository.isUserExists(id)
}
// But you can also write this way:
suspend fun isUserExists(id: String): Int {
@egorshustov
egorshustov / Coroutines1.kt
Last active December 21, 2018 12:29
Coroutines in UI example
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
progress_auth.visibility = View.VISIBLE
button_auth.setOnClickListener {
val actionBar = supportActionBar
GlobalScope.launch(Dispatchers.Main) {