Skip to content

Instantly share code, notes, and snippets.

View fergusonm's full-sized avatar

Michael Ferguson fergusonm

View GitHub Profile
@gmk57
gmk57 / Sending events to UI.kt
Last active February 13, 2024 15:17
Sending events to UI with Channel/Flow + custom collector (see my first comment for reasons behind it)
/**
* Starts collecting a flow when the lifecycle is started, and **cancels** the collection on stop.
* This is different from `lifecycleScope.launchWhenStarted { flow.collect{...} }`, in which case
* the coroutine is just suspended on stop.
*/
inline fun <reified T> Flow<T>.collectWhileStarted(
lifecycleOwner: LifecycleOwner,
noinline action: suspend (T) -> Unit
) {
object : DefaultLifecycleObserver {
@gmk57
gmk57 / 1 ViewBindingDelegates.kt
Last active January 25, 2024 09:01
Kotlin delegates for Android View Binding with usage examples
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.viewbinding.ViewBinding
@jamiesanson
jamiesanson / ViewLifecycleLazy.kt
Last active March 26, 2024 13:17
A Kotlin lazy implementation which automatically clears itself at appropriate times in the View Lifecycle, with a Fragment example
import androidx.fragment.app.Fragment
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
fun <T> Fragment.viewLifecycleLazy(initialise: () -> T): ReadOnlyProperty<Fragment, T> =
object : ReadOnlyProperty<Fragment, T>, DefaultLifecycleObserver {
/*
* Based on https://gist.github.com/jamiesanson/d1a3ed0910cd605e928572ce245bafc4
*
* Refactored to use the preferred `DefaultLifecycleObserver` which does not rely on the annotation processor.
* See https://developer.android.com/reference/kotlin/androidx/lifecycle/Lifecycle#init
*
* Usage:
* `private var binding: TheViewBinding by viewLifecycle()`
*/
@rubixhacker
rubixhacker / RxLiveData.kt
Created September 28, 2017 04:11
Kotlin extension functions to convert LiveData to and from a Flowable
// Add the following to your build.gradle file
// implementation "android.arch.lifecycle:reactivestreams:1.0.0-beta1"
import android.arch.lifecycle.LifecycleOwner
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.LiveDataReactiveStreams
import io.reactivex.Flowable
/**