Skip to content

Instantly share code, notes, and snippets.

Verifying my Blockstack ID is secured with the address 1Ngxnfmf64srg6vBwowVRg3ChCUaK7XUkQ https://explorer.blockstack.org/address/1Ngxnfmf64srg6vBwowVRg3ChCUaK7XUkQ
@gladed
gladed / ALog.kt
Last active October 27, 2017 00:58
import android.util.Log
/** In Kotlin: add `companion object : ALog` for `log.d { "message" }`-style logging. */
open class ALog {
val log = ALogger(javaClass.enclosingClass ?: javaClass)
companion object {
/** Decide if a statement should be printed based on its class and log level */
var filter: ((Class<*>, Int) -> Boolean) = { _, _ -> true }
}
@gladed
gladed / Closer.kt
Last active October 25, 2017 23:36
/**
* Wrap an object which requires closing if present
*/
open class Closer<T>(@Volatile private var wrapped: T? = null) {
/** Return the current wrapped value */
operator fun invoke(): T? = wrapped
/** If there is no value yet, store the result of [func] */
fun open(func: () -> T) = synchronized(this) {
class MyClass(val context: Context) {
private val wifiLock = Closer<WifiManager.MulticastLock>()
fun start() {
wifiLock.open {
// Create and open the lock (won't run if lock is already present)
val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
wifiManager.createMulticastLock("MyClass.lock").apply {
setReferenceCounted(true)
class MyClass {
@Volatile
var resource: Resource? = null
fun start() {
synchronized(this) {
resource ?: apply {
resource = Resource()
}
}
@gladed
gladed / MyClass.kt
Last active October 25, 2017 19:02
class MyClass {
var resource: Resource? = null // Something we need to use for a while
fun start() {
resource = Resource()
}
fun work() {
resource?.doSomething()
}