Scheduled Messages

The Compose UI components let users schedule a message from the composer and manage their scheduled messages: edit them, change their time, send them right away, or delete them. This page describes what the components show, how to turn them off, how to replace each part, and how to open the scheduled messages screen.

The scheduled messages UI components are available from version 7.22.0 of the stream-chat-android-compose artifact.

For how scheduled messages work on the server and in the low-level client (limits, statuses, failure reasons, events), see the Scheduled Messages guide.

When the UI shows

The scheduling UI shows only when both of these are true:

  • The current user has the schedule-message capability in the channel. Stream returns it only when scheduled messages are enabled for your app. See the Scheduled Messages guide to enable them.
  • ComposerConfig.scheduledMessagesEnabled is true. This is the default.

Without the capability, the send button has no long press action. The banner then shows only scheduled messages that failed to send, for example when the user lost the capability because the channel was frozen. You don't need any code for this.

What shows by default

When you use ChannelScreen, the SDK adds the scheduling from the composer, the banner and the snackbar described below. The bound MessageComposer with its MessageComposerViewModel adds only the scheduling from the composer. Your app opens the scheduled messages screen itself.

Scheduling from the composer

A long press on the send button opens the schedule sheet. The sheet lists quick dates in the user's time zone: tomorrow at 9:00, tomorrow at 13:00, and the first Monday after tomorrow at 9:00. A quick date sooner than the channel's earliest send time, or later than its latest, is left out, so the sheet can show fewer quick dates, or none. A Custom time row opens a second sheet with a preview of the message and Date and Time rows that open the Material date and time pickers. That sheet also says the time zone the message is sent in, and why the message can't be scheduled when it can't. When the channel limit is known and the user already has messages scheduled in the channel, it also shows how many, out of the limit.

The long press works only for a new message with content in the composer. It is not available while the user edits a sent message or while a command is active. The default send button also exposes the action to screen readers as a named accessibility action, so users don't need a long press.

The sheets check the limits and lead times from the channel config before they send the request: a time that is too soon or too far ahead, the channel or user limit, and a message that starts with a / command in a channel with commands. The message is saved on the device first, so a user can schedule it while offline. Once it is saved, the composer is emptied.

The banner above the composer

ChannelScreen shows a banner above the composer when the user has scheduled messages there. In the channel, the banner is about all the scheduled messages of the channel, thread replies included. In an open thread, it is about the scheduled replies of that thread. It shows one state at a time:

  • Some scheduled messages failed to send. This state also shows when the user can no longer schedule messages in the channel.
  • The channel limit is reached, so no new message can be scheduled in it.
  • The date of the scheduled message when there is only one, or how many messages or replies are scheduled.

The banner hides while the composer shows mention or command suggestions. It can be clicked, with a View or View all link, only when you pass onScheduledMessagesBannerClick to ChannelScreen. See Opening the scheduled messages screen.

When a message scheduled while offline reaches the server after its time has passed, the server sends it right away. ChannelScreen then shows a "Scheduled message sent" snackbar with a View action that scrolls to the message.

The scheduled messages screen

ScheduledMessagesScreen lists the current user's scheduled messages, sorted by the date they are sent at. Each item shows the date, the channel name and avatar, a preview of the message, and its status while it is sending, uploading or failed. The screen also has a loading state, an empty state, and an error state with a button to try again.

A search input above the list keeps the messages whose text, attachment titles or names, channel name (or channel ID when the channel isn't known), or names of the other channel members contain the query. The search ignores case and the spaces around the query. When the user has scheduled messages but none matches, the list shows an empty search state.

A click on an item opens a sheet with the actions its status allows:

Status Actions
Scheduled Edit message, Reschedule, Send now, Delete
Failed: the server could not send it Edit message, Reschedule, Delete
Failed: its channel was deleted Copy text, Delete
Failed: a change was refused, or did not reach the server Edit message, Reschedule, Delete
Sending, or its attachments are uploading None (a snackbar asks the user to wait)

When the server refuses a change because it is already sending the message, or because the message can no longer be changed, only Delete is left. When the message quotes a deleted message, Reschedule and Send now are removed until an edit removes the quote.

When the channel saved on the device shows that the user can no longer schedule messages in it, for example because it was frozen, the message can't be edited, rescheduled or sent now. The sheet then offers Copy text and Delete, so the user can keep the text before deleting the message.

Reschedule opens the same date and time sheet as the composer. The server can't change a message it could not send, so for such a message Reschedule schedules a copy at the new date and deletes the failed message. When the server could not send a message because its quote was deleted, the row says to edit the message to remove the quote.

Send now shows a "Scheduled message sent" snackbar. While the device is offline or reconnecting, it shows "Sends when you're back online" instead, and the message is sent once the client is connected again.

Delete asks for confirmation first. A message that was already sent, or deleted on another device, leaves the list with a short notice.

Editing a scheduled message

Edit message opens a composer below the list with the content of the message. Its save button keeps the date of the message. For a message the server could not send, saving also asks for a new date, then schedules the message again as a new message and deletes the failed one. The channel of the message does not need to be open.

Saving is disabled while a save is in progress, while the message is no longer scheduled, while it quotes a deleted message (until the user removes the quote), and while it starts with a command in a channel with commands.

The edit composer is the SDK's MessageComposer, so it follows the ChatTheme around the screen. To make it look like the composer of your channel screen, wrap the screen in a ChatTheme with the same ChatUiConfig.

Turning the UI off

To remove the scheduling UI from the composer and the channel screen, set scheduledMessagesEnabled to false in ComposerConfig:

ChatTheme(
    config = ChatUiConfig(
        composer = ComposerConfig(
            scheduledMessagesEnabled = false,
        ),
    ),
) {
    ChannelScreen(viewModelFactory = viewModelFactory)
}

This turns off the long press on the send button, the banner, and the "Scheduled message sent" snackbar of ChannelScreen. It doesn't change ScheduledMessagesScreen or ScheduledMessageList, which still show their own snackbars, such as the one after Send now. It also doesn't change what the user can do through the API. To stop users from scheduling messages, remove the ScheduleMessage permission from their role or ask support to turn off the feature.

Opening the scheduled messages screen

The SDK doesn't decide where users reach the scheduled messages screen. You connect it to your navigation.

From the channel banner

Pass onScheduledMessagesBannerClick to ChannelScreen. When it is set, the banner can be clicked and shows a View or View all link. The callback gets the ID of the thread the banner is about, or null for the whole channel, thread replies included. The banner about the channel limit always passes null, because the limit is per channel.

ChannelScreen(
    viewModelFactory = viewModelFactory,
    onScheduledMessagesBannerClick = { parentMessageId ->
        // Open the scheduled messages of this channel, or of the thread
        openScheduledMessages(cid = channelId, parentMessageId = parentMessageId)
    },
)

ChatsScreen, the adaptive screen that shows the channel list and the channel side by side on large screens, has the same parameter. Its callback also gets the cid of the channel open in the detail pane:

ChatsScreen(
    onScheduledMessagesBannerClick = { cid, parentMessageId ->
        // Open the scheduled messages, for example in your own pane or a new screen
    },
)

With ScheduledMessagesScreen

ScheduledMessagesScreen is a full screen with a header, a back button, a search input and the list:

@Composable
public fun ScheduledMessagesScreen(
    viewModelFactory: ScheduledMessageListViewModelFactory = ScheduledMessageListViewModelFactory(),
    title: String = stringResource(R.string.stream_compose_scheduled_message_list_title),
    onBackPressed: () -> Unit = {},
)
  • viewModelFactory: Creates the ScheduledMessageListViewModel. By default, the screen shows the scheduled messages of every channel.
  • title: The title of the header. Defaults to "Scheduled messages".
  • onBackPressed: Called when the user taps the back button.

Use ScheduledMessageListViewModelFactory to choose which scheduled messages the screen shows:

// The scheduled messages of every channel
ScheduledMessageListViewModelFactory()

// The scheduled messages of one channel, thread replies included
ScheduledMessageListViewModelFactory(cid = "messaging:general")

// The scheduled replies of one thread
ScheduledMessageListViewModelFactory(cid = "messaging:general", parentMessageId = parentMessageId)

For example, an Activity that shows the scheduled messages of a channel or a thread:

class ScheduledMessagesActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val cid = intent.getStringExtra(KEY_CID)
        val parentMessageId = intent.getStringExtra(KEY_PARENT_MESSAGE_ID)

        setContent {
            ChatTheme {
                ScheduledMessagesScreen(
                    viewModelFactory = ScheduledMessageListViewModelFactory(
                        cid = cid,
                        parentMessageId = parentMessageId,
                    ),
                    onBackPressed = ::finish,
                )
            }
        }
    }
}

In your own screen

To use your own header or place the list inside another layout, use ScheduledMessageList with a ScheduledMessageListViewModel. The list keeps all the default behavior: the actions sheet, the delete confirmation, the edit composer and the notices. It shows the messages that match the view model's search query, so to add a search input of your own, call viewModel.setSearchQuery(query) when the user types.

private val viewModelFactory by lazy {
    ScheduledMessageListViewModelFactory(cid = channelId)
}

private val viewModel by viewModels<ScheduledMessageListViewModel> { viewModelFactory }

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    setContent {
        ChatTheme {
            Column {
                MyHeader()
                ScheduledMessageList(
                    viewModel = viewModel,
                    modifier = Modifier.fillMaxSize(),
                )
            }
        }
    }
}

To build your own list instead, read the state from the view model and call its actions:

  • state: A StateFlow<ScheduledMessageListState> with the items, isLoading, isLoadFailed, the searchQuery, and the searchResults (the items that match the query, or all of them when the query is blank). Each ScheduledMessageItemState has the scheduledMessage, its channel, the quotedMessage, and the actions its status allows.
  • events: A Flow<ScheduledMessageListEvent> with the results to tell the user: MessageGone, DeletedMessageAlreadySent, SentNow (Send now was asked while the client was connected, so the message is sent right away), SendNowQueued (Send now was asked while the client was offline or reconnecting, so the message is sent once the client is connected again) and ActionFailed.
  • load(): Loads the scheduled messages again after they failed to load.
  • setSearchQuery(query): Searches the scheduled messages. The names it searches are the ones of the channel summary, not the ones a ChannelNameFormatter shows.
  • reschedule(id, scheduledAt), sendNow(id) and delete(id): Act on the scheduled message with that ID.

The view model has no edit method. In the UI components, editing a scheduled message is only available in ScheduledMessageList.

Customization

All the scheduled messages UI is drawn by the ChatComponentFactory. Override a method to replace one part, and keep the default behavior of the others.

Method Description
ScheduleMessageSheet The sheet opened by a long press on the send button, with the quick dates and the custom time row.
ScheduleMessageTimeSheet The sheet to pick a date and a time, used to schedule a new message and to reschedule one.
ScheduledMessagesBanner The banner above the composer.
ScheduledMessageListItem An item of the scheduled message list.
ScheduledMessageListEmptyContent The content of the list when there are no scheduled messages.
ScheduledMessageListLoadingContent The content of the list while the scheduled messages load.
ScheduledMessageListErrorContent The content of the list when the scheduled messages could not be loaded.
ScheduledMessageListSearchInput The search input of the scheduled messages screen, above the list.
ScheduledMessageListEmptySearchContent The content of the list when no scheduled message matches the search query.
ScheduledMessageActionsSheet The sheet with the actions on a scheduled message.
ScheduledMessageDeleteDialog The dialog that asks to confirm the deletion of a scheduled message.

The schedule sheets

ScheduleMessageSheetParams has:

  • dates: The quick dates, in the user's time zone. Dates outside the channel's lead times are left out, so the list can be empty.
  • state: The ScheduleMessageState of the channel. When state.isChannelLimitReached is true, the default sheet disables the options.
  • onDateClick: Call it with the date the user picked.
  • onCustomTimeClick: Call it to open the date and time sheet.
  • onDismiss: Call it when the sheet is dismissed.

ScheduleMessageTimeSheetParams has:

  • message: The message to schedule or reschedule, for the preview.
  • channelName: The name of the channel, for the preview.
  • initialDate: The date the pickers start at.
  • state: The ScheduleMessageState of the channel, for the lead times and the channel count.
  • error: A ScheduleMessageError that prevents scheduling whatever the date, or the error of the last request, or null. The default sheet shows a failed request (ScheduleMessageError.Failed) only while the picked date has no error.
  • onConfirm: Call it with the picked date.
  • onDismiss: Call it when the sheet is dismissed.
  • scheduledAt: The current date of the message to reschedule, or null to schedule a new message.

ScheduleMessageState describes what the composer knows about scheduling in the channel: canSchedule, the pending counts and limits (pendingInChannel, maxPerChannel, pendingForUser, maxPerUser), the lead times (minLeadTimeSeconds, maxLeadTimeSeconds) and hasCommands. Use state.dateError(date) to check a picked date in your own sheet. It returns ScheduleMessageError.TooSoon, ScheduleMessageError.TooFar or null.

For example, a quick sheet that offers only one date:

class CustomChatComponentFactory : ChatComponentFactory {

    @Composable
    override fun ScheduleMessageSheet(params: ScheduleMessageSheetParams) {
        ModalBottomSheet(onDismissRequest = params.onDismiss) {
            val firstDate = params.dates.firstOrNull()
            if (firstDate != null) {
                TextButton(
                    enabled = !params.state.isChannelLimitReached,
                    onClick = { params.onDateClick(firstDate) },
                ) {
                    Text("Send at the first quick date")
                }
            }
            TextButton(onClick = params.onCustomTimeClick) {
                Text("Pick a time")
            }
        }
    }
}

The banner

ScheduledMessagesBannerParams has the state to show, an onClick that is null when the banner can't be clicked, and a modifier.

ScheduledMessagesBannerState has three states: Failed (with the count of failed messages), LimitReached (with the count and the limit), and Scheduled (with the count, the nextScheduledAt date, and isInThread). Each state has the parentMessageId of the thread it is about, or null for the channel, thread replies included. More states can be added in a minor version, so a when on it needs an else branch.

class CustomChatComponentFactory : ChatComponentFactory {

    @Composable
    override fun ScheduledMessagesBanner(params: ScheduledMessagesBannerParams) {
        val text = when (val state = params.state) {
            is ScheduledMessagesBannerState.Failed -> "${state.count} failed"
            is ScheduledMessagesBannerState.LimitReached -> "Limit of ${state.limit} reached"
            is ScheduledMessagesBannerState.Scheduled -> "${state.count} scheduled"
            else -> return
        }
        val onClick = params.onClick
        Text(
            text = text,
            modifier = params.modifier.then(
                if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier,
            ),
        )
    }
}

ChannelScreen places the banner above bottomBarContent, so the banner stays when you replace the composer. To show the banner in a screen of your own, collect MessageComposerViewModel.scheduledMessagesBannerState and pass its value to ChatTheme.componentFactory.ScheduledMessagesBanner. It is null when there is nothing to show. It does not read ComposerConfig.scheduledMessagesEnabled, so check that flag yourself.

The scheduled message list

  • ScheduledMessageListItemParams has the item (a ScheduledMessageItemState), the currentUser and an onClick that opens the actions sheet.
  • ScheduledMessageListEmptyContentParams and ScheduledMessageListLoadingContentParams have a modifier.
  • ScheduledMessageListErrorContentParams has an onRetryClick and a modifier.
  • ScheduledMessageListSearchInputParams has the query, an onValueChange to call with the new query, and a modifier.
  • ScheduledMessageListEmptySearchContentParams has the searchQuery that no message matches, and a modifier.
  • ScheduledMessageActionsSheetParams has the item, the default actions to show in order, an onActionClick to call with the picked ScheduledMessageAction, an onDismiss, and the app's customActions (empty by default).
  • ScheduledMessageDeleteDialogParams has the channelName, an onConfirm and an onDismiss.

ScheduledMessageAction has the actions Edit, Reschedule, SendNow, EditAndReschedule, CopyText and Delete. More actions can be added in a minor version, so a when on it needs an else branch.

To add actions of your own, override ScheduledMessageActionsSheet and call the default sheet with customActions. Each ScheduledMessageCustomAction has a title, an icon, an onClick and isDestructive (false by default; true shows the action in the error color). The sheet shows your actions right before Delete, or after the default actions when there is no Delete, and closes before it calls onClick. The sheet doesn't open while the message is sending or its attachments are uploading, so your actions don't show then.

class CustomChatComponentFactory : ChatComponentFactory {

    @Composable
    override fun ScheduledMessageActionsSheet(params: ScheduledMessageActionsSheetParams) {
        val scheduledMessage = params.item.scheduledMessage
        super.ScheduledMessageActionsSheet(
            params.copy(
                customActions = listOf(
                    ScheduledMessageCustomAction(
                        title = "Share",
                        icon = painterResource(R.drawable.ic_share),
                        onClick = { shareText(scheduledMessage.message.text) },
                    ),
                ),
            ),
        )
    }
}

To replace the sheet, for example to show the actions in a dialog:

class CustomChatComponentFactory : ChatComponentFactory {

    @Composable
    override fun ScheduledMessageActionsSheet(params: ScheduledMessageActionsSheetParams) {
        AlertDialog(
            onDismissRequest = params.onDismiss,
            confirmButton = {},
            text = {
                Column {
                    params.actions.forEach { action ->
                        val label = when (action) {
                            ScheduledMessageAction.Edit,
                            ScheduledMessageAction.EditAndReschedule,
                            -> "Edit message"
                            ScheduledMessageAction.Reschedule -> "Reschedule"
                            ScheduledMessageAction.SendNow -> "Send now"
                            ScheduledMessageAction.CopyText -> "Copy text"
                            ScheduledMessageAction.Delete -> "Delete"
                            else -> return@forEach
                        }
                        TextButton(onClick = { params.onActionClick(action) }) {
                            Text(label)
                        }
                    }
                }
            },
        )
    }
}

A custom send button or trailing content

The default send button gets the schedule action as MessageComposerSendButtonParams.onLongClick, with its accessibility label in onLongClickLabel. It is null when scheduling is not available: the user has no schedule-message capability, scheduledMessagesEnabled is false, a sent message is edited, or a command is active. When the channel limit is reached, it is still set, and the sheet shows the options disabled. If you override MessageComposerSendButton, call onLongClick on a long press to keep scheduling:

class CustomChatComponentFactory : ChatComponentFactory {

    @Composable
    override fun MessageComposerSendButton(params: MessageComposerSendButtonParams) {
        Box(
            modifier = Modifier.combinedClickable(
                onClick = params.onClick,
                onClickLabel = params.onClickLabel,
                onLongClick = params.onLongClick,
                onLongClickLabel = params.onLongClickLabel,
            ),
        ) {
            Icon(imageVector = Icons.AutoMirrored.Filled.Send, contentDescription = null)
        }
    }
}

If you override MessageComposerInputTrailingContent, the schedule action is in MessageComposerInputTrailingContentParams.onSendLongClick. Pass it to your send button as onLongClick.

Scheduling the message yourself

The bound MessageComposer schedules the message through MessageComposerViewModel.scheduleMessage by default. To add your own logic, pass onScheduleMessage and call onResult with the result. The sheet closes on success and shows the error on failure.

MessageComposer(
    viewModel = composerViewModel,
    onScheduleMessage = { message, scheduledAt, onResult ->
        // Your own logic, for example analytics
        composerViewModel.scheduleMessage(message, scheduledAt, onResult)
    },
)

The date format

The scheduled messages list, the banner and the reschedule sheet format the date a message is sent at with formatScheduledDate of ChatTheme.dateFormatter. The default DateFormatter.from(context) shows the day and the time, like "Fri, Oct 23 at 9:00 AM". A DateFormatter of your own that doesn't override formatScheduledDate shows the medium date and the short time, like "Oct 23, 2026, 9:00 AM". To change it, pass a DateFormatter that overrides formatScheduledDate:

class CustomDateFormatter(
    private val default: DateFormatter,
) : DateFormatter by default {

    override fun formatScheduledDate(date: Date): String =
        SimpleDateFormat("EEEE, d MMMM 'at' HH:mm", Locale.getDefault()).format(date)
}

ChatTheme(
    dateFormatter = CustomDateFormatter(DateFormatter.from(context)),
) {
    // Your UI content
}

Texts

All the texts of the scheduled messages UI are Android string resources that start with stream_compose_schedule_message_ and stream_compose_scheduled_message. The default date format joins the day and the time with stream_ui_scheduled_message_date. To change them, override the resources in your app. See Localization.