Skip to content
/ ktx Public

Kotlin extension functions (that aren't included in the ktx libraries by Google)

License

Notifications You must be signed in to change notification settings

percula/ktx

Repository files navigation

ktx

Release License

Kotlin extension functions that complement Google's ktx library.

Features

Coroutine Context Helpers

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 }

ListLiveData

Notifies observers each time the list is updated:

val listLiveData: ListLiveData<String> = listLiveDataOf()

Collection.replaceWith() and Map.replaceWith()

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)

Collection.contains { }

Returns true if an element matches the expression within { }:

list.contains { it.startsWith("t") }

enumSafeValueOf()

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

Map.filterNotNullValues()

Removes all entries with null values

map.filterNotNullValues()

Menu.filter { }

Removes all menu items that do not match the expression with { }:

menu.filter { it.isChecked }

String extensions

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)

Lazy view bindings

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)

How to use

  1. Add the Jitpack repository to your project build.gradle:
allprojects {
    repositories {
        maven { url "https://jitpack.io" }
    }
  1. Add a dependency on the library in your app build.gradle:
dependencies {
    implementation 'com.github.percula:ktx:LATEST-VERSION'
}

About

Kotlin extension functions (that aren't included in the ktx libraries by Google)

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages