Last active
October 26, 2018 11:11
-
-
Save vitoksmile/b07a0000f13cebfeb1502d9be5c8eccb to your computer and use it in GitHub Desktop.
Saving values to Koin's property with delegating
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.koin.standalone.KoinComponent | |
import org.koin.standalone.getKoin | |
import kotlin.reflect.KProperty | |
class KoinPropertyDelegate<R, T : Any>(private val key: String, private val default: T) : | |
KoinComponent { | |
operator fun getValue(thisRef: R, property: KProperty<*>): T { | |
return getKoin().getProperty<Any>(key, default) as T | |
} | |
operator fun setValue(thisRef: R, property: KProperty<*>, value: T) { | |
getKoin().setProperty(key, value) | |
} | |
} | |
inline fun <reified R, T : Any> property(key: String, default: T) = | |
KoinPropertyDelegate<R, T>(key, default) | |
/** | |
* -------------------------------------------------------------- | |
*/ | |
/** | |
* Example | |
*/ | |
data class FilterParams( | |
val sort: Sort | |
) { | |
enum class Sort { | |
A_Z, | |
Z_A, | |
DATE_ASC, | |
DATE_DESC | |
} | |
} | |
class Test { | |
private var property: FilterParams by property( | |
key = "filter", | |
default = FilterParams(FilterParams.Sort.A_Z) | |
) | |
fun main(args: Array<String>) { | |
/** | |
* Getting | |
* Now sort == A_Z | |
*/ | |
doWork(property.sort) | |
// Setting | |
property = FilterParams(FilterParams.Sort.Z_A) | |
/** | |
* Getting | |
* Now sort == Z_A | |
*/ | |
doWork(property.sort) | |
SomeAction().doNewWork() | |
/** | |
* Getting | |
* Now sort == DATE_ASC | |
*/ | |
doWork(property.sort) | |
} | |
private fun doWork(sort: FilterParams.Sort) { | |
when (sort) { | |
FilterParams.Sort.A_Z -> { | |
} | |
FilterParams.Sort.Z_A -> { | |
} | |
FilterParams.Sort.DATE_ASC -> { | |
} | |
FilterParams.Sort.DATE_DESC -> { | |
} | |
} | |
} | |
} | |
class SomeAction { | |
private var property: FilterParams by property( | |
key = "filter", | |
default = FilterParams(FilterParams.Sort.A_Z) | |
) | |
fun doNewWork() { | |
/** | |
* Getting | |
* Now sort == Z_A | |
*/ | |
property.sort | |
// Setting | |
property = FilterParams(FilterParams.Sort.DATE_ASC) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment