Beautiful way to access touch interactions in Jetpack Compose

Abhishek Jangra
2 min readMar 28, 2023

--

Hey!

If you are trying to implement touch events with Jetpack Compose, this article could prove helpful.

While I was working on creating a custom button with Jetpack Compose, I had to code a scaling animation where the button becomes smaller when pressed, giving a visual feedback to the user.

Now, I don’t need to mention how complex the touch events api was with XML views. Also you could not put multiple listeners.

Theory

But with Compose the interaction events are decoupled from the View itself, instead the composables hold a state in the form of MutableInteractionSource.

MutableInteractionSource represents a stream of Interactions corresponding to events emitted by a component. ~ Android Developer Docs

Application

With Compose, when you want to make something respond to clicks, you can just add the clickable modifier which takes a method to call when the click happens. Internally it holds a MutableInteractionSource used to keep track of any interactions that might happen.

With composables, if your modifier holds any state, it is considered a good idea to expose it outside as well. And clickable does that, if you pass an instance of MutableInteractionSource , it will be used to hold data related to all the touch events and you can access them as well.

And that let’s us finish our scaling animation as shown below. You can use this interaction source anywhere you want to reach the button’s events, everything will be in sync without you having to set up custom streams.

This was a crisp write up based on information from topics I am working on currently, there will be more of these coming in the future so make sure you follow!

--

--