Skip to content

Instantly share code, notes, and snippets.

View gpeal's full-sized avatar

Gabriel Peal gpeal

View GitHub Profile
val progress by animateLottieCompositionAsState(
composition,
iterations = LottieConstants.IterateForever,
)
val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.heart))
data class Person(val age: Int? = null)
val people = listOf(
Person(5),
Person(null),
)
// Before/Your Dart example equivalent:
val firstAge = people.first { it.age != null }.age
// firstAge is of type Int? even though logically you know that it's Int.
@gpeal
gpeal / wifiBroadcastReceiver.kt
Created March 14, 2021 02:46
Broadcast Receiver
context.registerReceiverInScope(scope, WifiManager.WIFI_STATE_CHANGED_ACTION) { intent ->
val state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_DISABLED)
// Use wifi state here
}
@gpeal
gpeal / Label.kt
Created March 14, 2021 02:36
Unique Observable Usage
class Label @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
var inverted by uniqueObservable(false) { refreshDrawableState() }
...
}
@gpeal
gpeal / uniqueObservable.kt
Created March 14, 2021 02:34
Unique Observable
/**
* Like Delegates.observable except it only calls the callback when the value actually changes.
*/
public inline fun <T> uniqueObservable(initialValue: T, emitInitial: Boolean = false, crossinline onChange: (value: T) -> Unit): ReadWriteProperty<Any?, T> {
if (emitInitial) onChange(initialValue)
return object : ObservableProperty<T>(initialValue) {
override fun afterChange(property: KProperty<*>, oldValue: T, newValue: T) {
if (oldValue != newValue) onChange(newValue)
}
}
@Composable
fun MyComposable() {
val viewModel: MyViewModel = mavericksViewModel()
val state by viewModel.collectAsState()
AnotherComposable(
state.value,
onClick = viewModel.onClick()
)
}
// Will fade myView in or out.
// You can call this repeatedly with the same value and it won't interrupt the ongoing animation.
myView.fadeTo(true)
myView.fadeTo(false)
myView.fadeTo(true, toAlpha = 0.8f)
myView.fadeTo(true, startDelay = 300)
myView.fadeTo(true, duration = 500)
recyclerView.updatePadding(top = 14.dp.toInt())
@gpeal
gpeal / dp.kt
Last active November 2, 2021 18:03
/**
* Call this function on a dp value and it will return the equivalent
* number of pixels for the current display.
* e.g. 8.dp
*/
val Number.dp get() = toFloat() * (Resources.getSystem().displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)