Skip to content

Instantly share code, notes, and snippets.

@nhaarman
nhaarman / ktlint
Last active December 18, 2020 07:25
A Gradle wrapper-like ktlint wrapper
#!/bin/bash
ktlint_version="0.40.0"
########################################################################
# A wrapper for ktlint which automatically downloads and runs ktlint.
# ktlint executables will be installed under `build/ktlint`.
#
# Usage
#
# Download and run ktlint, passing arguments:
@nhaarman
nhaarman / MainActivity.java
Created December 28, 2018 08:35
MainActivity
package com.nhaarman.android2sandbox;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class MainActivity extends Activity {
static int i = 0;
class PaymentFlowNavigator private constructor(
private var shippingInfo: ShippingInfo? = null,
savedState: SavedState?
): StackNavigator(savedState),
ShippingInfoScreen.Events,
PaymentInfoScreen.Events,
ConfirmationScreen.Events {
override fun initialStack() = listOf(ShoppingCartScreen())
interface Navigator {
fun addListener(listener: Events)
fun saveInstanceState() : SavedState
interface Events {
fun screen(screen: Screen<out Container)
class SelectPictureScreen(
private val listener: Events
) : Screen<SelectPictureContainer> {
override fun attach(c: SelectPictureContainer) {
c.setOnPictureClickListener { listener.onPictureSelected(it.id) }
}
interface Events {
fun onPictureSelected(id: Long)
interface SimpleContainer {
var text: String
}
class SimpleScreen(
val name: String
) : Screen<SimpleContainer> {
override fun attach(v: SimpleContainer) {
v.text = "Hello, $name!"
@nhaarman
nhaarman / Screen.kt
Created September 3, 2018 21:08
A very simple contract for a screen in a mobile application.
interface Screen<V : Container> {
fun onStart() {}
fun attach(v: V) {}
fun detach(v: V) {}
fun onStop() {}
fun onDestroy() {}
data class Device(
val name: String
)
interface DeviceScanner {
/** Emits a Device opon each new discovery event */
fun devices() : Observable<Device>
}
class BluetoothDeviceScanner(
@nhaarman
nhaarman / UndoRedo.kt
Created March 7, 2018 13:54
Simple Rx undo/redo stream
fun <T, R> Observable<Command<T>>.undoRedo(initialValue: R, accumulator: (R, T) -> R): Observable<R> {
return this
.scan(UndoRedoStack.create<T>()) { stack, command ->
when (command) {
is Command.Do -> stack.push(command.action)
is Command.Undo -> stack.undo()
is Command.Redo -> stack.redo()
}
}
.map { stack ->
sealed class Distance : Comparable<Distance> {
data class DistanceMeters(val value: Float) : Distance()
data class DistanceFeet(val value: Float) : Distance()
fun toMeters() = when (this) {
is DistanceMeters -> this
is DistanceFeet -> DistanceMeters(value * .3048f)
}
fun toFeet() = when (this) {