Is there a way to tell is a composable running in ...
# compose
v
Is there a way to tell is a composable running in an initial composition or a recomposition? I’m building yet another screen transition composable based on
Crossfade
and I want it not animate anything on initial composition
I can only think about a hack with
remember
Copy code
@Composable
private fun isInitialComposition(): Boolean {
    var isInitialComposition by remember { mutableStateOf(true) }
    return isInitialComposition.also { isInitialComposition = false }
}
But maybe there is a conventional way to do this?
s
@Doris Liu for animations @Leland Richardson [G] for clever composition tricks 🙂
z
I think you can do something like
currentComposer.isInserting
- true means it’s the first composition. But for this case, that feels like a hack. A lot of the animation tools already won’t animate when their target is the same as their starting value.
a
not sure I'd count on that composer API sticking around as public
d
You could initialize a value with something that is not meaningful. For example, if you build animations based on
CrossFade
, you could initialize its internal state to null (
Copy code
var state : CrossfadeState<T>? by remember { mutableStateOf(null) }
), and update it after your first-run logic.
l
currentComposer.inserting
is the most correct and efficient way to do this but I'd be curious to see exactly how you're using it
1
v
Thanks for all responses! I’ll try
currentComposer.inserting
in a moment and share my code with you guys
Sorry for delay, here is what I came up with: https://gist.github.com/vganin/4e846beb8913c70b4886693102ac4b47 (props to mr. @cb, I based my solution on his old gist)
z
I’m no expert on the transition animation apis, but my instinct is that if you have to use
inserting
with it, there’s probably a better way to write your animation logic, or the apis are missing a feature.
a
yeah the
inserting
is likely to be acting as a proxy for some other animation state that you probably want to hoist explicitly and construct into a particular initial state to determine this behavior
inserting
seems like the most correct and efficient way to answer what is likely to be the wrong question 🙂
d
I would suggest setting the initState (for initializing
TransitionAnimation
) using the same logic as how you determine target state here. That way when you call
toState()
in the first composition, you'll get an no-op, as the target state is the same as the initial state.
Cool implementation BTW. 👍
🙏 1
v
Thanks for your ideas with initial state, really appreciated! I managed to get away from using
inserting
by setting appropriate initial state in
remember
closure. If you are interested, here is what changed: https://gist.github.com/vganin/4e846beb8913c70b4886693102ac4b47/revisions#diff-79f7b006e814e81e4584b239fd3c45426def70b13bf091e5a6b1c0911bedd108
🎉 1