Skip to content

Commit

Permalink
Add Modifier.thenIfNotNull, OnChange
Browse files Browse the repository at this point in the history
  • Loading branch information
w2sv committed May 8, 2024
1 parent 7baab72 commit e45ecd6
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package com.w2sv.composed
import android.annotation.SuppressLint
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.FlowCollector
import kotlinx.coroutines.flow.collectLatest
Expand Down Expand Up @@ -37,4 +39,18 @@ fun <T> CollectLatestFromFlow(
LaunchedEffect(flow, key1, key2) {
flow.collectLatest(action)
}
}

@Composable
fun <T> OnChange(
value: T,
key1: Any? = null,
key2: Any? = null,
callback: suspend (T) -> Unit
) {
val updatedCallback by rememberUpdatedState(newValue = callback)

LaunchedEffect(value, key1, key2) {
updatedCallback(value)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,13 @@ inline fun Modifier.thenIf(
condition: Boolean,
onTrue: Modifier.() -> Modifier,
): Modifier =
thenIf(condition = condition, onFalse = { this }, onTrue = onTrue)
thenIf(condition = condition, onFalse = { this }, onTrue = onTrue)

/**
* A convenience function that invokes the Modifier receiver function [onNotNull] which depends on an optional [instance], if that [instance] is not null.
*/
inline fun <T> Modifier.thenIfNotNull(
instance: T?,
onNotNull: Modifier.(T) -> Modifier,
): Modifier =
instance?.let { onNotNull(it) } ?: this

0 comments on commit e45ecd6

Please sign in to comment.