Skip to content

Instantly share code, notes, and snippets.

Avatar

Robin roschlau

View GitHub Profile
@roschlau
roschlau / GridSpacingDecoration.java
Created Sep 7, 2016
An ItemDecoration that assigns even spacing to a grid of items, with the spacing between the items the same size as the outer spacing of the grid.
View GridSpacingDecoration.java
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public class GridSpacingDecoration extends RecyclerView.ItemDecoration {
private int cols;
private int spacing;
public GridSpacingDecoration(int cols, int spacing) {
@roschlau
roschlau / DiffUtilCallback.kt
Last active Mar 5, 2017
Default implementation of a DiffUtil.Callback
View DiffUtilCallback.kt
import android.support.v7.util.DiffUtil
open class DiffUtilCallback<T>(val oldList: List<T>, val newList: List<T>) : DiffUtil.Callback() {
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int)
= oldList[oldItemPosition] == newList[newItemPosition]
override fun getOldListSize()
= oldList.size
@roschlau
roschlau / Repeater.kt
Last active Mar 16, 2017
A simple repeater that will repeat an action infinitely with a set interval until it is stopped. Uses Coroutines.
View Repeater.kt
class Repeater(val interval: Long,
val context: CoroutineContext = UI,
val block: () -> Unit
) {
private var updatingJob: Job? = null
private val updatingJobLock = Any()
fun start() = synchronized(updatingJobLock) {
if (updatingJob != null && updatingJob!!.isActive) {
return
@roschlau
roschlau / event.kt
Last active Jul 7, 2017 — forked from orangy/event.kt
C#-style events in Kotlin
View event.kt
class Event<T> {
private val handlers = arrayListOf<(T) -> Unit>()
operator fun plusAssign(handler: (T) -> Unit) { handlers.add(handler) }
operator fun invoke(value: T) { for (handler in handlers) handler(value) }
}
val e = Event<String>() // define event
fun main(args : Array<String>) {
e += { println(it) } // subscribe
@roschlau
roschlau / memoized.kt
Created Sep 21, 2017
Simple function to memoize function calls
View memoized.kt
fun <T, U> memoized(function: (T) -> U): (T) -> U {
val cache = mutableMapOf<T, U>()
return { t -> cache.getOrPut(t) { function(t) } }
}
@roschlau
roschlau / MutableLazy.kt
Last active Nov 26, 2017
Lazy Delegate implementation for a mutable, but lazily initialized variable
View MutableLazy.kt
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* Property delegate to allow lazy initialization of a mutable variable.
*/
class MutableLazy<T>(val init: () -> T) : ReadWriteProperty<Any?, T> {
private var value: Optional<T> = Optional.None()
@roschlau
roschlau / BaseActivity.kt
Last active Mar 19, 2018
Utility class for handling permissions on Android
View BaseActivity.kt
class BaseActivity : Activity {
val permissionHandler: PermissionRequestHandler
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
val handled = permissionHandler.onRequestPermissionsResult(requestCode, permissions, grantResults)
if(!handled) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
@roschlau
roschlau / ImmutableHelpers.kt
Created Mar 19, 2018
Some helpers for working with immutable collections in Kotlin
View ImmutableHelpers.kt
/**
* Returns a new List with the element at [fromIndex] moved to [toIndex]
*/
private fun <T> List<T>.move(fromIndex: Int, toIndex: Int) = this.mapIndexed { index, element -> when {
index == toIndex -> this[fromIndex]
fromIndex < toIndex && index in fromIndex..toIndex -> this[index + 1]
fromIndex > toIndex && index in toIndex..fromIndex -> this[index - 1]
else -> element
} }
@roschlau
roschlau / DeferPanicRecover.kt
Last active Aug 16, 2018
Implementing the defer, panic and recover functions from golang in Kotlin, because reasons. I have hardly any knowledge of Go, I googled a little bit about how those functions work. The example is copied from https://blog.golang.org/defer-panic-and-recover and results in exactly the same output.
View DeferPanicRecover.kt
import java.util.Optional
// Actual implementation
fun <T> deferringScope(block: DeferringScope<T>.() -> T): Optional<T> {
val scope = DeferringScope<T>()
try {
scope.result = Optional.of(scope.block())
} catch (e: Throwable) {
scope.error = e.message ?: e.toString()
}
@roschlau
roschlau / ValueTypes.kt
Created Sep 8, 2018
A collection of type wrappers that work similar to Kotlin's inline classes, but for Kotlin < 1.3
View ValueTypes.kt
import java.util.UUID
/**
* Superclass for classes that wrap a single value for type safety purposes.
*/
abstract class WrapperType<T : Any>(val value: T) {
override fun toString() = value.toString()
override fun equals(other: Any?) = other is WrapperType<*> && value == other.value
override fun hashCode() = value.hashCode()
}