https://kotlinlang.org logo
#compose
Title
# compose
m

Michal Klimczak

11/01/2021, 3:31 PM
Crossfade animation with custom diff lambda 🧵
I have some sealed class for state and it can be different data classes, e.g.
Copy code
data class SearchSuggestions(
        override val searchPhrase: String,
        val suggestions: List<String>
    ) : ShopScreenState(), HasSearchPhrase

    data class SearchRecents(
        override val searchPhrase: String,
        val recentSearches: List<String>
    ) : ShopScreenState(), HasSearchPhrase
Now I want a nice crossfade when
SearchSuggestions
changes into
SearchRecents
and vice versa. But don't want the crossfade to "blink" every time e.g.
SearchRecents
changes to a different
SearchRecents
I don't want to get rid of data class magic, too, it's useful in other places. Its equals should not change. What I want is to compare different states myself and only then crossfade one state to another, but still be able to use the whole state internally, e.g. like this
Copy code
Crossfade(state, diff = { previousState, newState -> previousState::class != newState::class }){ 
   when(it)... //`it` should still be ShopScreenState, so that it's smartcasted and preserved across animation
}
am I missing something obvious?
(CC: @Doris Liu, hope you don't mind)
I guess I can do my own Crossfade, but if what I wrote makes sense, I wonder if I should also file a feature request
d

Doris Liu

11/01/2021, 5:37 PM
Thanks for the request. We have recently added the support for
contentKey
in AnimatedContent, where the
contentKey
can be defined for each target, and is being used for diffing. You can use that for your use cases. The support in crossfade is coming, tracked here: https://issuetracker.google.com/197907070 In the meantime, I'd encourage you to try out
contentKey
and let us know if you have any other feature requests. See https://developer.android.com/reference/kotlin/androidx/compose/animation/package-summary#(androidx.compose.animation[…].Function1,kotlin.Function2)
❤️ 2
m

Michal Klimczak

11/01/2021, 5:55 PM
Awesome, thank you Doris!
(I starred the issue, I assume it concerns the crossfade as well and another issue is not required)
d

Doris Liu

11/01/2021, 5:57 PM
Yup. No need to file another issue. 🙂
t

Thomas

11/02/2021, 8:10 PM
@Doris Liu I just took a look at
contentKey
and it should do exactly what I want. Thanks for adding it! However, it looks like you missed a function. Is there a reason
contentKey
was not added here? https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/[…]ent.kt;l=119-129;drc=4b91a7fe67a0a791829b42dbccb4e80f7beaaf74
d

Doris Liu

11/02/2021, 8:13 PM
Thanks for the follow-up @Thomas . We didn't add contentKey to
AnimatedContent
(i.e. non-extension fun version) intentionally to keep that version simple and therefore easy to learn.
👍 1
3 Views