Skip to content

Instantly share code, notes, and snippets.

View bholota's full-sized avatar

Bartłomiej Hołota bholota

View GitHub Profile
import android.app.Activity
import android.support.annotation.IdRes
import android.view.View
fun <T : View> Activity.bind(@IdRes idRes: Int): Lazy<T> {
@Suppress("UNCHECKED_CAST")
return unsafeLazy { findViewById(idRes) as T }
}
fun <T : View> View.bind(@IdRes idRes: Int): Lazy<T> {
@bholota
bholota / LifecycleCoroutines.kt
Created November 29, 2018 14:39 — forked from LouisCAD/LifecycleCoroutines.kt
CoroutineScope and Job integration with Lifecycle for Android. Meant to be used for your coroutines in lifecycle aware components. Ongoing PR: https://github.com/Kotlin/kotlinx.coroutines/pull/760
import android.arch.lifecycle.GenericLifecycleObserver
import android.arch.lifecycle.Lifecycle
import android.arch.lifecycle.Lifecycle.Event.ON_DESTROY
import android.arch.lifecycle.LifecycleOwner
import kotlinx.coroutines.experimental.CoroutineScope
import kotlinx.coroutines.experimental.Dispatchers
import kotlinx.coroutines.experimental.Job
import kotlinx.coroutines.experimental.android.Main
fun Lifecycle.createJob(cancelEvent: Lifecycle.Event = ON_DESTROY): Job {
class ForegroundServiceLauncher(private val serviceClass: Class<out Service>) {
private var isStarting = false
private var shouldStop = false
@Synchronized
fun startService(context: Context, block: Intent.() -> Unit = {}) {
isStarting = true
shouldStop = false
ContextCompat.startForegroundService(context, Intent(context, serviceClass).apply { block() })
class SampleService : Service() {
companion object {
private val LAUNCHER = ForegroundServiceLauncher(SampleService::class.java)
@JvmStatic
fun start(context: Context) = LAUNCHER.startService(context)
@JvmStatic
fun stop(context: Context) = LAUNCHER.stopService(context)
}