Jetpack Compose Integration
The StorifyMe Android SDK provides native Jetpack Compose support, allowing you to integrate stories seamlessly into your Compose-based applications. This integration offers a modern, declarative API that feels natural in Compose projects.
Why Use Native Compose Integration?
The native Compose integration provides several advantages over the traditional View-based approach:
- Declarative API: Use composable functions that fit naturally into your Compose UI
- Automatic Lifecycle Management: The widget handles lifecycle automatically with Compose's lifecycle
- Type-Safe Configuration: Use
remember*helper functions for configuration that survives recomposition - Per-Widget Callbacks: Set event callbacks directly on each widget instead of using a global listener
- Compose-Friendly Patterns: Works seamlessly with State, remember, LazyColumn, and other Compose features
Prerequisites
Before integrating StorifyMeWidget in Compose, ensure you have:
- SDK Version: StorifyMe Android SDK version
3.0.0or higher - Compose Version: Jetpack Compose BOM
2024.01.00or higher, or individual Compose dependencies at version1.6.0+ - SDK Initialization: StorifyMe SDK must be initialized before rendering StorifyMeWidget
You must initialize the StorifyMe SDK before using the StorifyMeWidget composable. Typically this is done in your Application class or MainActivity's onCreate before setContent.
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
StorifyMeSDK.init(
context = this,
apiKey = "your-api-key",
accountId = "your-account-id",
environment = StorifyMeEnvironment.EU // or StorifyMeEnvironment.US, StorifyMeEnvironment.DEV
)
}
}
Basic Usage
Simple Widget
The most basic way to add a widget to your Compose app is to provide just the widget ID:
import com.storify.android_sdk.ui.compose.StorifyMeWidget
@Composable
fun MyScreen() {
StorifyMeWidget(
widgetId = 12345,
modifier = Modifier.fillMaxWidth()
)
}
Make sure to replace 12345 with your actual widget ID. You can find your widget ID in the widget share dialog on the StorifyMe platform.
Widget with Padding
Add padding around the widget using standard Compose modifiers:
@Composable
fun MyScreen() {
Column {
StorifyMeWidget(
widgetId = 12345,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp)
)
}
}
Multiple Widgets
You can easily add multiple widgets to a screen:
@Composable
fun MyScreen() {
LazyColumn {
item {
Text("Featured Stories", style = MaterialTheme.typography.headlineMedium)
}
item {
StorifyMeWidget(
widgetId = 12345,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
)
}
item {
Text("Trending Stories", style = MaterialTheme.typography.headlineMedium)
}
item {
StorifyMeWidget(
widgetId = 67890,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
)
}
}
}
Simple Configuration
You can configure the widget using rememberStoriesViewConfig():
import com.storify.android_sdk.ui.compose.controller.rememberStoriesViewConfig
@Composable
fun MyScreen() {
val config = rememberStoriesViewConfig(
language = "en",
direction = StorifyMeContentDirection.LTR,
segments = listOf("premium", "vip")
)
StorifyMeWidget(
widgetId = 12345,
config = config,
modifier = Modifier.fillMaxWidth()
)
}
The remember* helper functions ensure your configuration survives recomposition. Always use these helpers instead of creating configuration objects directly.
Configuration Options
The StorifyMe Compose integration provides several configuration options to customize widget behavior, appearance, and media handling. All configuration uses remember* helper functions to ensure stability across recompositions.
Widget Configuration
Use rememberStoriesViewConfig() to configure language, direction, segments, experience IDs, and query parameters. If language is omitted, content defaults to the device language. When a widget's configuration changes, it reloads content from page one.
Language
Set a language explicitly when you do not want the device language default:
val config = rememberStoriesViewConfig(
language = "en" // or "es", "fr", "de", etc.
)
StorifyMeWidget(
widgetId = 12345,
config = config,
modifier = Modifier.fillMaxWidth()
)
Direction (RTL/LTR)
Control content direction for right-to-left languages:
import com.storify.android_sdk.shared.StorifyMeContentDirection
val config = rememberStoriesViewConfig(
direction = StorifyMeContentDirection.RTL // or LTR
)
StorifyMeWidget(
widgetId = 12345,
config = config,
modifier = Modifier.fillMaxWidth()
)
Segments (Tags)
Filter stories by segments/tags:
val config = rememberStoriesViewConfig(
segments = listOf("premium", "vip", "new-users")
)
StorifyMeWidget(
widgetId = 12345,
config = config,
modifier = Modifier.fillMaxWidth()
)
Segments allow you to show different stories to different user groups. You can manage segments in the StorifyMe platform.
Experience IDs
Limit the response to selected experience IDs:
val config = rememberStoriesViewConfig(
experienceIds = listOf(101L, 202L),
)
Theme
The widget follows the host app system theme by default. For a per-widget override, build the config with setTheme:
val config = remember {
StorifyMeWidgetConfig.Builder()
.setTheme(StorifyMeWidgetTheme.DARK)
.build()
}
StorifyMeWidget(widgetId = 12345L, config = config)
Use StorifyMeWidgetTheme.LIGHT for a light override. The effective theme is part of the content request and cache identity.
Customer ID
Set the customer ID globally when the signed-in user changes. StorifyMeWidgetConfig.Builder.setCustomerId(...) is deprecated.
LaunchedEffect(userId) {
StorifyMeSDK.instance.configureCustomerId(userId)
}
Query Parameters
Add custom query parameters to widget requests:
val queryParams = mapOf(
"source" to "mobile-app",
"campaign" to "summer-sale"
)
val config = rememberStoriesViewConfig(
queryParameters = queryParams
)
StorifyMeWidget(
widgetId = 12345,
config = config,
modifier = Modifier.fillMaxWidth()
)
Combined Configuration
Combine multiple configuration options:
val config = rememberStoriesViewConfig(
language = "en",
direction = StorifyMeContentDirection.LTR,
segments = listOf("premium", "vip"),
queryParameters = mapOf("source" to "mobile")
)
StorifyMeWidget(
widgetId = 12345,
config = config,
modifier = Modifier.fillMaxWidth()
)
Media Options
Control how media (GIFs and videos) is displayed in story posters using rememberMediaOptions():
Video Posters
Enable or disable video posters in the widget:
import com.storify.android_sdk.ui.compose.config.rememberMediaOptions
val mediaOptions = rememberMediaOptions(
videoPosterEnabled = true // Default: false
)
StorifyMeWidget(
widgetId = 12345,
mediaOptions = mediaOptions,
modifier = Modifier.fillMaxWidth()
)
By default, video posters are disabled to reduce data usage and improve performance. Enable them for richer previews.
GIF Posters
Control GIF poster display:
val mediaOptions = rememberMediaOptions(
gifPosterEnabled = false // Default: true
)
StorifyMeWidget(
widgetId = 12345,
mediaOptions = mediaOptions,
modifier = Modifier.fillMaxWidth()
)
GIF posters are enabled by default. Disable them to reduce data usage on slower connections.
Combined Media Options
Configure both video and GIF posters:
val mediaOptions = rememberMediaOptions(
videoPosterEnabled = true,
gifPosterEnabled = false
)
StorifyMeWidget(
widgetId = 12345,
mediaOptions = mediaOptions,
modifier = Modifier.fillMaxWidth()
)
Behavior Options
Customize story playback, audio, fullscreen mode, and URL handling using rememberBehaviorOptions():
The Compose BehaviorOptions API in 3.0.0 still accepts the deprecated 2.x StoryPlaybackBehaviour, StoryAudioBehaviour, and StoryAudioState enums. They remain supported in 3.x. The View navigator and direct handle API accept the v3 StorifyMeExperienceBehaviour with StorifyMeExperiencePlaybackBehaviour, StorifyMeExperienceAudioBehaviour, and StorifyMeExperienceAudioState.
Fullscreen Mode
Enable or disable fullscreen display for stories:
import com.storify.android_sdk.ui.compose.config.rememberBehaviorOptions
val behaviorOptions = rememberBehaviorOptions(
fullscreenEnabled = true // Default: false
)
StorifyMeWidget(
widgetId = 12345,
behaviorOptions = behaviorOptions,
modifier = Modifier.fillMaxWidth()
)
Fullscreen mode is particularly useful for shorts content where immersion enhances the viewing experience.
Audio Behavior
Control how audio state persists across stories:
import com.storify.android_sdk.shared.StoryAudioBehaviour
import com.storify.android_sdk.shared.StoryAudioState
val behaviorOptions = rememberBehaviorOptions(
audioBehaviour = StoryAudioBehaviour.APPLY_LAST_USER_CHANGE_FOR_ALL_FUTURE_STORIES,
audioDefaultState = StoryAudioState.MUTED
)
StorifyMeWidget(
widgetId = 12345,
behaviorOptions = behaviorOptions,
modifier = Modifier.fillMaxWidth()
)
Audio Behavior Options:
APPLY_LAST_USER_CHANGE_FOR_ALL_FUTURE_STORIES- Remember user's audio preference across all stories (default)APPLY_CHANGE_FOR_SINGLE_STORY- Audio changes only affect the current storyAPPLY_CHANGE_FOR_PRESENTED_STORIES- Audio changes affect currently loaded stories only
Audio Default States:
MUTED- Stories start mutedUNMUTED- Stories start with audio playing
Unmute on Volume Change
Automatically unmute stories when user changes device volume:
val behaviorOptions = rememberBehaviorOptions(
unmuteOnOutputVolumeChange = true // Default: false
)
StorifyMeWidget(
widgetId = 12345,
behaviorOptions = behaviorOptions,
modifier = Modifier.fillMaxWidth()
)
Playback Behavior
Control how story playback resumes:
import com.storify.android_sdk.shared.StoryPlaybackBehaviour
val behaviorOptions = rememberBehaviorOptions(
playbackBehaviour = StoryPlaybackBehaviour.ALWAYS_RESUME_STORY_WHERE_STOPPED
)
StorifyMeWidget(
widgetId = 12345,
behaviorOptions = behaviorOptions,
modifier = Modifier.fillMaxWidth()
)
Playback Behavior Options:
ALWAYS_RESUME_STORY_WHERE_STOPPED- Resume where user left off (default)RESTART_STORIES_ON_APP_LAUNCH- Restart stories on each app launchRESTART_STORIES_WHEN_OPEN- Restart stories each time they're opened
Story Item Pulse Animation
Enable or disable the pulse animation on story items:
val behaviorOptions = rememberBehaviorOptions(
storyItemPulseAnimationEnabled = true // Default: true
)
StorifyMeWidget(
widgetId = 12345,
behaviorOptions = behaviorOptions,
modifier = Modifier.fillMaxWidth()
)
URL Presentation
Control how URLs open within stories:
import com.storify.android_sdk.shared.StorifyMeURLPresentationBehaviour
val behaviorOptions = rememberBehaviorOptions(
urlPresentationBehaviour = StorifyMeURLPresentationBehaviour.IN_APP_BROWSER
)
StorifyMeWidget(
widgetId = 12345,
behaviorOptions = behaviorOptions,
modifier = Modifier.fillMaxWidth()
)
URL Presentation Options:
EXTERNAL_BROWSER- Open URLs in external browser (default)IN_APP_BROWSER- Open URLs in in-app browser
Combined Behavior Options
Configure multiple behavior options together:
val behaviorOptions = rememberBehaviorOptions(
fullscreenEnabled = true,
storyItemPulseAnimationEnabled = true,
audioBehaviour = StoryAudioBehaviour.APPLY_LAST_USER_CHANGE_FOR_ALL_FUTURE_STORIES,
audioDefaultState = StoryAudioState.MUTED,
unmuteOnOutputVolumeChange = true,
playbackBehaviour = StoryPlaybackBehaviour.ALWAYS_RESUME_STORY_WHERE_STOPPED,
urlPresentationBehaviour = StorifyMeURLPresentationBehaviour.IN_APP_BROWSER
)
StorifyMeWidget(
widgetId = 12345,
behaviorOptions = behaviorOptions,
modifier = Modifier.fillMaxWidth()
)
Progress Options
Control progress bar visibility using rememberProgressOptions():
import com.storify.android_sdk.ui.compose.config.rememberProgressOptions
val progressOptions = rememberProgressOptions(
showProgressBar = false // Default: true
)
StorifyMeWidget(
widgetId = 12345,
progressOptions = progressOptions,
modifier = Modifier.fillMaxWidth()
)
The progress bar is enabled by default to show story playback progress. Disable it for a cleaner, minimalist look.
Combining All Configuration Options
You can combine all configuration options in a single StorifyMeWidget:
@Composable
fun FullyConfiguredWidget() {
val config = rememberStoriesViewConfig(
language = "en",
direction = StorifyMeContentDirection.LTR,
segments = listOf("premium", "vip")
)
val mediaOptions = rememberMediaOptions(
videoPosterEnabled = true,
gifPosterEnabled = true
)
val behaviorOptions = rememberBehaviorOptions(
fullscreenEnabled = true,
audioBehaviour = StoryAudioBehaviour.APPLY_LAST_USER_CHANGE_FOR_ALL_FUTURE_STORIES,
audioDefaultState = StoryAudioState.MUTED,
playbackBehaviour = StoryPlaybackBehaviour.ALWAYS_RESUME_STORY_WHERE_STOPPED,
urlPresentationBehaviour = StorifyMeURLPresentationBehaviour.IN_APP_BROWSER
)
val progressOptions = rememberProgressOptions(
showProgressBar = true
)
StorifyMeWidget(
widgetId = 12345,
config = config,
mediaOptions = mediaOptions,
behaviorOptions = behaviorOptions,
progressOptions = progressOptions,
modifier = Modifier.fillMaxWidth()
)
}
Event Handling
The Compose API uses grouped callbacks. Use the v3 field names and typed payloads. Callback objects can be remembered when you need stable references across recompositions.
Load events
StorifyMeLoadEventCallbacks reports successful loads and failures:
val loadCallbacks = StorifyMeLoadEventCallbacks(
onLoaded = { widgetId, experiences ->
Log.d("Widget", "Loaded ${experiences.size} experiences for $widgetId")
},
onFailed = { error ->
Log.e("Widget", "Widget ${error.widgetId} failed: ${error.message}")
},
)
StorifyMeWidget(
widgetId = 12345L,
loadEventCallbacks = loadCallbacks,
)
Experience lifecycle and navigation
StorifyMeLifecycleCallbacks reports experience lifecycle events and navigation requests. Read the public StorifyMeExperience properties directly.
val lifecycleCallbacks = StorifyMeLifecycleCallbacks(
onOpened = { experience, index ->
Log.d("Widget", "Opened ${experience.name} at index $index")
},
onClosed = { experience ->
Log.d("Widget", "Closed ${experience.name}")
},
onFinished = { experience, index ->
analytics.track("experience_finished", experience.id)
},
onShared = { experience ->
analytics.track("experience_shared", experience.id)
},
onNavigationRequested = { experience, completion ->
val url = experience.navigationUrl
if (url != null && url.startsWith("myapp://")) {
appRouter.open(url)
completion(StorifyMeExperienceNavigationDecision.HANDLE_NAVIGATION)
} else {
completion(StorifyMeExperienceNavigationDecision.OPEN_EXPERIENCE)
}
},
)
StorifyMeWidget(
widgetId = 12345L,
lifecycleCallbacks = lifecycleCallbacks,
)
Ad events
val adCallbacks = StorifyMeAdCallbacks(
onAdDisplayed = { experience, index ->
adTracker.recordImpression(experience.id)
},
)
StorifyMeWidget(widgetId = 12345L, adCallbacks = adCallbacks)
Interaction and link events
StorifyMeInteractionCallbacks supplies typed action and analytics event objects. Use onLinkTriggered to handle links tapped inside the viewer.
val interactionCallbacks = StorifyMeInteractionCallbacks(
onAction = { action ->
Log.d("Widget", "Action ${action.type}: ${action.href}")
},
onEvent = { event ->
analytics.track(event.action, event.rawData)
},
onLinkTriggered = { url, completion ->
if (url.startsWith("myapp://")) {
appRouter.open(url)
completion(StorifyMeLinkTriggerCompletion.IGNORE_PRESENTING_LINK)
} else {
completion(StorifyMeLinkTriggerCompletion.OPEN_LINK_BY_DEFAULT)
}
},
)
StorifyMeWidget(
widgetId = 12345L,
interactionCallbacks = interactionCallbacks,
)
StorifyMeLinkTriggerCompletion controls links inside the viewer. For the experience's configured navigation URL, use StorifyMeLifecycleCallbacks.onNavigationRequested and StorifyMeExperienceNavigationDecision.
Commerce events
Use StorifyMeCommerceCallbacks for typed cart and checkout events:
val commerceCallbacks = StorifyMeCommerceCallbacks(
onCartItemAdded = { productId, quantity ->
cart.add(productId, quantity)
},
onCartUpdated = { cartSnapshot ->
syncCart(cartSnapshot)
},
onCheckout = { cartSnapshot ->
analytics.track("checkout", cartSnapshot.total, cartSnapshot.currency)
},
)
StorifyMeWidget(
widgetId = 12345L,
commerceCallbacks = commerceCallbacks,
)
Combine callbacks
Pass multiple callback groups to the same composable when a screen needs them:
StorifyMeWidget(
widgetId = 12345L,
loadEventCallbacks = loadCallbacks,
lifecycleCallbacks = lifecycleCallbacks,
interactionCallbacks = interactionCallbacks,
commerceCallbacks = commerceCallbacks,
adCallbacks = adCallbacks,
)
The older onLoad, onFail, and onStory... fields remain for 3.x compatibility. Use onLoaded, onFailed, and the lifecycle callback names shown here in new code. StorifyMeShoppingCallbacks is deprecated in favor of StorifyMeCommerceCallbacks.
Controller Usage
For advanced control over the widget, use rememberStoriesViewController() to access imperative operations and observe widget state.
Creating a Controller
import com.storify.android_sdk.ui.compose.controller.rememberStoriesViewController
@Composable
fun MyScreen() {
val controller = rememberStoriesViewController()
StorifyMeWidget(
widgetId = 12345,
controller = controller,
modifier = Modifier.fillMaxWidth()
)
}
Observing Widget State
The controller provides state flows for observing widget properties and server segments:
@Composable
fun MyScreen() {
val controller = rememberStoriesViewController()
// Observe widget properties (size, layout info)
val widgetProperties by controller.widgetProperties.collectAsState()
// Observe server segments
val serverSegments by controller.serverSegments.collectAsState()
Column {
// Display widget info
widgetProperties?.let { props ->
Text(
text = "Widget size: ${props.storyWidth}x${props.storyHeight}px",
style = MaterialTheme.typography.bodySmall
)
}
// Display segments
if (serverSegments.isNotEmpty()) {
Text(
text = "Active segments: ${serverSegments.joinToString()}",
style = MaterialTheme.typography.bodySmall
)
}
StorifyMeWidget(
widgetId = 12345,
controller = controller,
modifier = Modifier.fillMaxWidth()
)
}
}
Reload Widget
Programmatically reload the widget:
@Composable
fun MyScreen() {
val controller = rememberStoriesViewController()
Column {
Button(onClick = {
controller.load() // Reload the widget
}) {
Text("Reload Stories")
}
StorifyMeWidget(
widgetId = 12345,
controller = controller,
modifier = Modifier.fillMaxWidth()
)
}
}
Manual Pagination
Load more stories manually (useful for custom "Load More" buttons):
@Composable
fun MyScreen() {
val controller = rememberStoriesViewController()
val scope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() }
Scaffold(snackbarHost = { SnackbarHost(snackbarHostState) }) { padding ->
Column(modifier = Modifier.padding(padding)) {
StorifyMeWidget(
widgetId = 12345,
controller = controller,
modifier = Modifier.fillMaxWidth()
)
Button(
onClick = {
val hasMore = controller.loadMore()
scope.launch {
if (hasMore) {
snackbarHostState.showSnackbar("Loading more stories...")
} else {
snackbarHostState.showSnackbar("No more stories available")
}
}
},
modifier = Modifier.align(Alignment.CenterHorizontally)
) {
Text("Load More")
}
}
}
}
By default, StorifyMeWidget handles pagination automatically when users scroll. Manual pagination is only needed for custom UI implementations.
Open an experience by position
Programmatically open an experience by its index:
@Composable
fun MyScreen() {
val controller = rememberStoriesViewController()
Column {
Button(onClick = {
controller.openWidgetExperienceByPosition(0) { result ->
when (result) {
StorifyMeWidgetExperienceNavigatorExecutionResult.SUCCESS ->
Log.d("Widget", "Experience opened successfully")
StorifyMeWidgetExperienceNavigatorExecutionResult.NOT_FOUND ->
Log.e("Widget", "No experience at that position")
}
}
}) {
Text("Open First Story")
}
StorifyMeWidget(
widgetId = 12345,
controller = controller,
modifier = Modifier.fillMaxWidth()
)
}
}
Open an experience by handle
Open an experience using its unique handle:
@Composable
fun MyScreen() {
val controller = rememberStoriesViewController()
Column {
Button(onClick = {
controller.openWidgetExperienceByHandle("summer-sale-2024") { result ->
if (result == StorifyMeWidgetExperienceNavigatorExecutionResult.SUCCESS) {
Log.d("Widget", "Experience opened by handle")
}
}
}) {
Text("Open Summer Sale Story")
}
StorifyMeWidget(
widgetId = 12345,
controller = controller,
modifier = Modifier.fillMaxWidth()
)
}
}
Open an experience by ID
Open an experience using its ID:
@Composable
fun MyScreen() {
val controller = rememberStoriesViewController()
Column {
Button(onClick = {
controller.openWidgetExperienceById(12345L) { result ->
if (result == StorifyMeWidgetExperienceNavigatorExecutionResult.SUCCESS) {
Log.d("Widget", "Experience opened by ID")
}
}
}) {
Text("Open Story by ID")
}
StorifyMeWidget(
widgetId = 12345,
controller = controller,
modifier = Modifier.fillMaxWidth()
)
}
}
Advanced Features
Custom Data & Personalization
Dynamic Data (Integration Variables)
Pass dynamic data to stories for personalization:
import org.json.JSONObject
@Composable
fun PersonalizedWidget(userId: String, userName: String) {
val dynamicData = remember(userId, userName) {
mapOf(
"integration-id-1" to JSONObject().apply {
put("userName", userName)
put("userId", userId)
put("accountTier", "premium")
put("points", 1250)
},
"integration-id-2" to JSONObject().apply {
put("cartValue", 99.99)
put("itemCount", 3)
}
)
}
StorifyMeWidget(
widgetId = 12345,
dynamicData = dynamicData,
modifier = Modifier.fillMaxWidth()
)
}
Create integration variables in the StorifyMe platform, then pass their values dynamically from your app. This enables personalized content for each user.
Segment User ID
Pass a user ID for CDP audience segmentation:
@Composable
fun SegmentedWidget(userId: String) {
StorifyMeWidget(
widgetId = 12345,
segmentUserId = userId, // For audience segment resolution
modifier = Modifier.fillMaxWidth()
)
}
Pull-to-Refresh Integration
Integrate with Material 3's PullToRefreshBox:
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RefreshableWidget() {
val controller = rememberStoriesViewController()
var isRefreshing by remember { mutableStateOf(false) }
PullToRefreshBox(
isRefreshing = isRefreshing,
onRefresh = {
isRefreshing = true
controller.load()
}
) {
StorifyMeWidget(
widgetId = 12345,
controller = controller,
loadEventCallbacks = StorifyMeLoadEventCallbacks(
onLoaded = { _, _ ->
isRefreshing = false
},
onFailed = { _ ->
isRefreshing = false
}
),
modifier = Modifier.fillMaxWidth()
)
}
}
Height Caching for LazyColumn
When using multiple widgets in a LazyColumn, enable height caching to prevent scroll jumping:
@Composable
fun OptimizedList() {
LazyColumn {
items(5) { index ->
StorifyMeWidget(
widgetId = (100L + index),
enableHeightCache = true, // Prevents scroll jumping
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
)
}
}
}
The SDK caches the measured height of each widget in the session. When widgets are disposed and recreated (during scrolling), the cached height provides a size hint to LazyColumn, preventing unexpected scroll position changes.
Multiple Widgets Management
Manage multiple widgets with different configurations:
@Composable
fun MultiWidgetScreen() {
LazyColumn {
// Featured stories - premium users only
item {
Text(
"Featured Stories",
style = MaterialTheme.typography.headlineMedium,
modifier = Modifier.padding(16.dp)
)
}
item {
val config = rememberStoriesViewConfig(
segments = listOf("premium", "featured")
)
StorifyMeWidget(
widgetId = 101,
config = config,
enableHeightCache = true,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
)
}
// Trending stories - all users
item {
Text(
"Trending Now",
style = MaterialTheme.typography.headlineMedium,
modifier = Modifier.padding(16.dp)
)
}
item {
val config = rememberStoriesViewConfig(
segments = listOf("trending")
)
StorifyMeWidget(
widgetId = 102,
config = config,
enableHeightCache = true,
lifecycleCallbacks = StorifyMeLifecycleCallbacks(
onOpened = { experience, _ ->
// Track trending story views
analytics.logEvent("trending_story_viewed")
}
),
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
)
}
// Regional stories
item {
Text(
"Local Stories",
style = MaterialTheme.typography.headlineMedium,
modifier = Modifier.padding(16.dp)
)
}
item {
val config = rememberStoriesViewConfig(
segments = listOf("local", "en-US")
)
StorifyMeWidget(
widgetId = 103,
config = config,
enableHeightCache = true,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
)
}
}
}
Practical Examples
Here are complete, real-world examples demonstrating common use cases:
Example 1: Basic Widget
The simplest integration:
@Composable
fun BasicWidget() {
StorifyMeWidget(
widgetId = 12345,
modifier = Modifier.fillMaxWidth()
)
}
Example 2: Widget with Load Tracking
Track story loading and display count:
@Composable
fun TrackedWidget() {
val scope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() }
var loadedCount by remember { mutableIntStateOf(0) }
Scaffold(snackbarHost = { SnackbarHost(snackbarHostState) }) { padding ->
Column(modifier = Modifier.padding(padding)) {
if (loadedCount > 0) {
Text(
text = "$loadedCount stories available",
modifier = Modifier.padding(8.dp)
)
}
StorifyMeWidget(
widgetId = 12345,
loadEventCallbacks = StorifyMeLoadEventCallbacks(
onLoaded = { _, stories ->
loadedCount = stories.size
},
onFailed = { error ->
scope.launch {
snackbarHostState.showSnackbar("Error: ${error.message}")
}
}
),
modifier = Modifier.fillMaxWidth()
)
}
}
}
Example 3: Widget with Analytics
Track story interactions with your analytics platform:
@Composable
fun AnalyticsWidget(userId: String) {
val config = rememberStoriesViewConfig(
language = "en",
segments = listOf("premium"),
queryParameters = mapOf("userId" to userId)
)
val lifecycleCallbacks = StorifyMeLifecycleCallbacks(
onOpened = { experience, index ->
analytics.logEvent("story_opened", bundleOf(
"story_id" to experience.id.toString(),
"story_name" to experience.name,
"position" to index
))
},
onFinished = { experience, _ ->
analytics.logEvent("story_completed", bundleOf(
"story_id" to experience.id.toString()
))
}
)
StorifyMeWidget(
widgetId = 12345,
config = config,
lifecycleCallbacks = lifecycleCallbacks,
modifier = Modifier.fillMaxWidth()
)
}
Example 4: Widget with Deep Link Handling
Handle app deep links and product navigation:
@Composable
fun DeepLinkWidget(navController: NavController) {
val interactionCallbacks = StorifyMeInteractionCallbacks(
onLinkTriggered = { url, completion ->
when {
url.startsWith("myapp://product/") -> {
val productId = url.substringAfter("myapp://product/")
navController.navigate("product/$productId")
completion(StorifyMeLinkTriggerCompletion.IGNORE_PRESENTING_LINK)
}
url.startsWith("myapp://") -> {
navController.navigate(url.substringAfter("myapp://"))
completion(StorifyMeLinkTriggerCompletion.IGNORE_PRESENTING_LINK)
}
else -> {
completion(StorifyMeLinkTriggerCompletion.OPEN_LINK_BY_DEFAULT)
}
}
}
)
StorifyMeWidget(
widgetId = 12345L,
interactionCallbacks = interactionCallbacks,
modifier = Modifier.fillMaxWidth()
)
}
Example 5: Widget with Controller
Programmatic control with reload and navigation:
@Composable
fun ControlledWidget() {
val controller = rememberStoriesViewController()
val widgetProperties by controller.widgetProperties.collectAsState()
Column {
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.padding(8.dp)
) {
Button(onClick = { controller.load() }) {
Text("Reload")
}
Button(onClick = {
controller.openWidgetExperienceByPosition(0) { result ->
Log.d("Widget", "Result: $result")
}
}) {
Text("Open First")
}
}
widgetProperties?.let {
Text(
"Size: ${it.storyWidth}x${it.storyHeight}",
modifier = Modifier.padding(8.dp),
style = MaterialTheme.typography.bodySmall
)
}
StorifyMeWidget(
widgetId = 12345,
controller = controller,
modifier = Modifier.fillMaxWidth()
)
}
}
Example 6: Pull-to-Refresh Widget
Swipe down to refresh stories:
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RefreshableWidgetExample() {
val controller = rememberStoriesViewController()
var isRefreshing by remember { mutableStateOf(false) }
PullToRefreshBox(
isRefreshing = isRefreshing,
onRefresh = {
isRefreshing = true
controller.load()
}
) {
StorifyMeWidget(
widgetId = 12345,
controller = controller,
loadEventCallbacks = StorifyMeLoadEventCallbacks(
onLoaded = { _, _ -> isRefreshing = false },
onFailed = { _ -> isRefreshing = false }
),
modifier = Modifier.fillMaxWidth()
)
}
}
Best Practices
1. Always Use remember* Helper Functions
Use the provided helper functions to ensure configuration survives recomposition:
// Good - Config is remembered
val config = rememberStoriesViewConfig(
segments = listOf("premium")
)
// Bad - Config is recreated on every recomposition
val config = StorifyMeWidgetConfig.Builder()
.setSegments(listOf("premium"))
.build()
2. Keep Widget IDs Stable
Widget IDs should be stable across recompositions:
// Good - Stable widget ID
@Composable
fun MyWidget() {
StorifyMeWidget(widgetId = 12345)
}
// Careful - Widget recreates when state changes
@Composable
fun DynamicWidget(count: Int) {
StorifyMeWidget(widgetId = count.toLong()) // Recreates on every count change
}
3. Leverage Automatic Lifecycle Management
The widget automatically handles lifecycle - no manual cleanup needed:
// Correct - Automatic lifecycle management
@Composable
fun MyScreen() {
StorifyMeWidget(widgetId = 12345)
} // Widget disposed automatically when leaving composition
4. Use Stable Callbacks
Create stable callback references to avoid unnecessary recomposition:
// Good - Stable callback
@Composable
fun MyWidget() {
val loadCallbacks = remember {
{ widgetId: Long, experiences: List<StorifyMeExperience> ->
Log.d("Widget", "Loaded $widgetId")
}
}
StorifyMeWidget(
widgetId = 12345L,
loadEventCallbacks = StorifyMeLoadEventCallbacks(onLoaded = loadCallbacks),
)
}
// Bad - New callback on every recomposition
@Composable
fun MyWidget() {
StorifyMeWidget(
widgetId = 12345L,
loadEventCallbacks = StorifyMeLoadEventCallbacks(onLoaded = { widgetId, experiences ->
Log.d("Widget", "Loaded $widgetId")
}),
)
}
5. Use Modifiers for Layout Control
Let Compose modifiers handle layout and styling:
StorifyMeWidget(
widgetId = 12345,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
)
6. Enable Height Caching for Lists
When using widgets in LazyColumn, enable height caching:
LazyColumn {
items(10) { index ->
StorifyMeWidget(
widgetId = (100L + index),
enableHeightCache = true, // Prevents scroll jumping
modifier = Modifier.fillMaxWidth()
)
}
}
7. Handle Errors Gracefully
Always provide error handling:
StorifyMeWidget(
widgetId = 12345,
loadEventCallbacks = StorifyMeLoadEventCallbacks(
onFailed = { error ->
Log.e("Widget", "Load failed: ${error.message}")
// Show error UI or retry
}
)
)
Migration from View-Based Integration
Comparison: XML View vs Compose
| Aspect | XML View | Compose |
|---|---|---|
| Integration | Add to XML layout | Use composable function |
| Configuration | Builder pattern (StorifyMeWidgetConfig.Builder()) | Helper functions (rememberStoriesViewConfig()) |
| Event Listeners | Focused widget and experience listeners | Per-widget callback groups |
| Lifecycle | Manual (in Activity/Fragment) | Automatic (Compose lifecycle) |
| Updates | Imperative (storiesView.load()) | Declarative recomposition |
Migration Steps
1. XML Layout to Composable
Before (XML):
<com.storify.android_sdk.StorifyMeWidget
android:id="@+id/storiesView"
android:layout_width="match_parent"
android:layout_height="150dp" />
// Activity
val storiesView = findViewById<StorifyMeWidget>(R.id.storiesView)
storiesView.widgetId = 12345
storiesView.load()
After (Compose):
@Composable
fun MyScreen() {
StorifyMeWidget(
widgetId = 12345,
modifier = Modifier.fillMaxWidth()
)
}
2. Configuration Builder to Helper Functions
Before (View):
val config = StorifyMeWidgetConfig.Builder().apply {
setLanguage("en")
setDirection(StorifyMeContentDirection.LTR)
setSegments(listOf("premium", "vip"))
}.build()
storiesView.config = config
After (Compose):
val config = rememberStoriesViewConfig(
language = "en",
direction = StorifyMeContentDirection.LTR,
segments = listOf("premium", "vip")
)
StorifyMeWidget(widgetId = 12345, config = config)
3. Global Event Listener to Per-Widget Callbacks
Before (View):
// Global listener affects all widgets
StorifyMe.instance.eventListener = object : StorifyMeEventListener() {
override fun onLoad(stories: List<StoryWithSeen>) {
Log.d("Widget", "Loaded ${stories.size} stories")
}
override fun onStoryOpened(story: StoryWithSeen, index: Int) {
Log.d("Widget", "Story opened: ${story.story.name}")
}
}
After (Compose):
// Per-widget callbacks
StorifyMeWidget(
widgetId = 12345,
loadEventCallbacks = StorifyMeLoadEventCallbacks(
onLoaded = { widgetId, stories ->
Log.d("Widget", "Loaded")
}
),
lifecycleCallbacks = StorifyMeLifecycleCallbacks(
onOpened = { experience, index ->
Log.d("Widget", "Story opened")
}
)
)
4. Imperative Operations to Controller
Before (View):
val storiesView = findViewById<StorifyMeWidget>(R.id.storiesView)
// Reload
storiesView.load()
// Open story
storiesView.openWidgetExperienceByPosition(0) { result ->
// Handle result
}
After (Compose):
val controller = rememberStoriesViewController()
// Reload
controller.load()
// Open story
controller.openWidgetExperienceByPosition(0) { result ->
// Handle result
}
StorifyMeWidget(widgetId = 12345, controller = controller)
Complete Migration Example
Before (Activity with XML):
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val storiesView = findViewById<StorifyMeWidget>(R.id.storiesView)
val config = StorifyMeWidgetConfig.Builder().apply {
setLanguage("en")
setSegments(listOf("premium"))
}.build()
storiesView.config = config
storiesView.widgetId = 12345
storiesView.load()
StorifyMe.instance.eventListener = object : StorifyMeEventListener() {
override fun onLoad(stories: List<StoryWithSeen>) {
Toast.makeText(this@MainActivity, "Loaded ${stories.size} stories", Toast.LENGTH_SHORT).show()
}
override fun onStoryOpened(story: StoryWithSeen, index: Int) {
Log.d("Stories", "Opened: ${story.story.name}")
}
}
}
}
After (Compose):
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyAppTheme {
StoriesScreen()
}
}
}
}
@Composable
fun StoriesScreen() {
val scope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() }
val config = rememberStoriesViewConfig(
language = "en",
segments = listOf("premium")
)
Scaffold(snackbarHost = { SnackbarHost(snackbarHostState) }) { padding ->
StorifyMeWidget(
widgetId = 12345,
config = config,
loadEventCallbacks = StorifyMeLoadEventCallbacks(
onLoaded = { _, stories ->
scope.launch {
snackbarHostState.showSnackbar("Loaded ${stories.size} stories")
}
}
),
lifecycleCallbacks = StorifyMeLifecycleCallbacks(
onOpened = { experience, _ ->
Log.d("Stories", "Opened: ${experience.name}")
}
),
modifier = Modifier
.fillMaxWidth()
.padding(padding)
)
}
}
Key Differences Summary
- Declarative vs Imperative: Compose uses a declarative approach where you describe what the UI should look like
- Lifecycle: Compose handles lifecycle automatically - no need for
onDestroycleanup - Per-Widget Callbacks: Each widget can have its own callbacks instead of a global listener
- Type Safety:
remember*helpers provide better type safety and prevent common mistakes - State Management: Compose's state system makes it easier to update UI based on data changes
Summary
The StorifyMe Jetpack Compose integration provides a modern, declarative API for integrating stories into your Compose applications. Key features include:
- Native Compose Support: First-class composable functions
- Automatic Lifecycle: No manual cleanup required
- Type-Safe Configuration: Use
remember*helpers for stable configuration - Per-Widget Callbacks: Fine-grained event handling
- Advanced Features: Controller, personalization, pull-to-refresh, height caching
- Easy Migration: Clear path from View-based to Compose
For additional help, refer to the View-based documentation or the Configuration and Events guides.