Kotlin extension functions that complement Google's ktx library.
Switch between coroutine contexts easily:
Before:
withContext(Dispatchers.IO) { databaseQueryFunction() }
.let { withContext(Dispatchers.Main) { liveData.value = it } }
With ktx:
onIO{ databaseQueryFunction() }.onMain { liveData.value = it }
Notifies observers each time the list is updated:
val listLiveData: ListLiveData<String> = listLiveDataOf()
Replaces a list or maps contents with the contents of another list or map:
val list = mutableListOf<String>("test")
val newList = listOf("new","items","in","list")
list.replaceWith(newList)
Returns true if an element matches the expression within { }:
list.contains { it.startsWith("t") }
Returns the enum entry with the specified name, returning null if nothing matches:
enum class DAY { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
enumSafeValueOf<DAY>("TUESDAY") // REturns DAY.TUESDAY
enumSafeValueOf<DAY>("NOTADAY") // Returns null
Removes all entries with null values
map.filterNotNullValues()
Removes all menu items that do not match the expression with { }:
menu.filter { it.isChecked }
fun String.removeSymbols() // removes non-ASCII symbols and replaces with � (or user specified symbol)
fun String.containsAny(vararg strings: String)
fun String.capitalizeWords()
fun String.camelCaseWords()
fun String.trimTo(length: Int)
fun List<String>.containsCaseInsensitive(string: String)
fun List<String>.indexCaseInsensitive(string: String)
Note: If the view is recreated, these will point to an old reference. Thus, I do not recommend using these extensions for most situations.
val recyclerView by bind<RecyclerView>(R.id.recycler_view)
- Add the Jitpack repository to your project build.gradle:
allprojects {
repositories {
maven { url "https://jitpack.io" }
}
- Add a dependency on the library in your app build.gradle:
dependencies {
implementation 'com.github.percula:ktx:LATEST-VERSION'
}