Skip to content

Instantly share code, notes, and snippets.

@ozgurg
Created August 16, 2022 23:38
Show Gist options
  • Save ozgurg/092362eb7d3ba560f4750b9a1f2a3ef6 to your computer and use it in GitHub Desktop.
Save ozgurg/092362eb7d3ba560f4750b9a1f2a3ef6 to your computer and use it in GitHub Desktop.
Useful Kotlin extensions
fun <T> MutableList<T>.addOrRemove(item: T) {
if (this.contains(item)) {
this.remove(item)
} else {
this.add(item)
}
}
fun <T> MutableList<T>.findIndex(predicate: (T) -> Boolean): Int {
val item = this.find(predicate)
return this.indexOf(item)
}
fun <R> CoroutineScope.asyncTask(
onPreExecute: () -> Unit,
doInBackground: () -> R,
onPostExecute: (R) -> Unit
) = launch {
onPreExecute()
val result = withContext(Dispatchers.IO) {
doInBackground()
}
onPostExecute(result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment