Skip to content

Instantly share code, notes, and snippets.

View leonardoaramaki's full-sized avatar
🛰️

Leonardo Aramaki leonardoaramaki

🛰️
View GitHub Profile
@leonardoaramaki
leonardoaramaki / Debouncer.kt
Created November 16, 2021 16:59
Add click debouncing logic to Jetpack Compose
/**
* Wraps an [onClick] lambda with another one that supports debouncing. The default deboucing time
* is 1000ms.
*
* @return debounced onClick
*/
@Composable
inline fun debounced(crossinline onClick: () -> Unit, debounceTime: Long = 1000L): () -> Unit {
var lastTimeClicked by remember { mutableStateOf(0L) }
val onClickLambda: () -> Unit = {
@leonardoaramaki
leonardoaramaki / recyclerview_fixed_scroll.kt
Last active April 19, 2021 09:08
Keep RecyclerView vertical scroll offset after layout resizing due to the keyboard being shown.
private var verticalScrollOffset = AtomicInteger(0)
recyclerView.addOnLayoutChangeListener { _, _, _, _, bottom, _, _, _, oldBottom ->
val y = oldBottom - bottom
if (y.absoluteValue > 0) {
recyclerView.post {
if (y > 0 || verticalScrollOffset.get().absoluteValue >= y.absoluteValue) {
recyclerView.scrollBy(0, y)
} else {
recyclerView.scrollBy(0, verticalScrollOffset.get())
Thread.setDefaultUncaughtExceptionHandler ({ t, e -> //… })
// Java
@FunctionaInterface
public interface UncaughtExceptionHandler {
void uncaughtException(Thread t, Throwable e);
}
fun fail(message: String): Nothing {
val throwable = Throwable(message)
Thread.setDefaultUncaughtExceptionHandler { t, e -> System.err.println(e.message) }
throw throwable
}
// ...
val user: User = getUser() ?: fail("User not found!")
println("Hello, ${user.name}")
fun fail(message: String): Nothing {
throw IllegalStateException(message)
}
// ...
val user: User = getUser() ?: fail("User not found!")
println("Hello, ${user.name}")
fun fail(message: String) {
throw IllegalStateException(message)
}
// Is the same as:
fun fail(message: String): Unit {
throw IllegalStateException(message)
}
fun fail(message: String) {
throw IllegalStateException(message)
}
….
val user: User = getUser() ?: fail("User not found!")
println("Hello, ${user.name}")
val user: User = getUser() ?: throw IllegalStateException("User not found!")
println("Hello, ${user.name}")
fun getUser(): User? {
// ...
}
val user: User? = getUser()
if (user != null) {
println("Hello, ${user.name}")
} else {
throw IllegalStateException("User not found!")
}