Star Feedback Widget with Compose and a ViewModel
Data Structure DesignModel answerLast updated
Build a Compose feedback form with a 1-5 star selector, a capped comment field and an async submit, driven by a single ViewModel state stream that survives rotation and double taps.
Task
Build a small feedback widget for an Android app using Kotlin and Jetpack Compose. Users pick a star score from 1 to 5, optionally type a comment, and send both to a backend. Structure it with MVVM and unidirectional data flow: the UI renders state and reports events, and a ViewModel owns the state.
What to build
1. StarRatingBar (stateless)
- Inputs:
rating: Int(0 means nothing chosen),onRatingChanged: (Int) -> Unit,modifier, andmaxStars: Int = 5. - Draws
maxStarstappable icons: filled up to the current rating, outlined after it. - Tapping star
kreportskthrough the callback. The component holds no state of its own.
2. RatingCardScreen
- Shows the star bar and a comment field limited to 280 characters, with a live counter in the form
"{current}/{max}". - Shows a Submit button, disabled when the rating is 0, the comment is over 280 characters, or a submission is already running.
- Reflects the submission lifecycle:
- Loading: a
CircularProgressIndicatorreplaces or sits inside the button. - Success: the card is replaced by "Thank you for your feedback!" plus a Reset action.
- Error: an inline banner or Snackbar shows the message with a Retry option.
- Loading: a
3. RatingViewModel
- Exposes exactly one read-only
StateFlowof UI state. - Supports
setRating(Int),updateComment(String),submit()andreset(). - Fakes the backend with a suspend function (for example
delay(1000), optionally failing at random).
Required types
data class RatingUiState(
val rating: Int = 0,
val comment: String = "",
val submissionStatus: SubmissionStatus = SubmissionStatus.Idle,
val errorMessage: String? = null
) {
val isValid: Boolean
get() = rating in 1..5 && comment.length <= 280
}
sealed interface SubmissionStatus {
object Idle : SubmissionStatus
object Loading : SubmissionStatus
object Success : SubmissionStatus
object Error : SubmissionStatus
}
@Composable
fun StarRatingBar(
rating: Int,
onRatingChanged: (Int) -> Unit,
modifier: Modifier = Modifier,
maxStars: Int = 5
)
@Composable
fun RatingCardScreen(
viewModel: RatingViewModel = viewModel(),
modifier: Modifier = Modifier
)
Cases your design must handle
- Several fast taps on Submit before the first call finishes must not send duplicate requests.
- Rotating the device must keep the draft rating and comment and must not fire a new request.
- Pasting more than 280 characters must be either truncated or clearly flagged as invalid.
Write the code and explain why your design handles each case.
Hints
Hint 1
Keep all business state in the ViewModel's single immutable state object. Make the star bar and a `RatingCardContent(state, callbacks)` composable fully stateless, so the screen composable is only a thin wrapper that collects the flow.
Hint 2
Disabling the button is not enough to stop double submits, because two taps can arrive before recomposition. Do the check and the move to `Loading` in one atomic `MutableStateFlow.update {}` and only launch the coroutine if that transition succeeded.
Hint 3
Launch the request from the click handler inside `viewModelScope`, never from composition, so rotation cannot restart it. Also decide what happens on `reset()` during loading (cancel the job), whether edits are allowed while loading, and never surface a `CancellationException` as an error.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core idea is unidirectional data flow. The loop is: the UI emits an event, the ViewModel computes a new immutable RatingUiState, one StateFlow publishes it, and Compose redraws from it. Composables keep no business state.
Layering
StarRatingBar: stateless. Takesrating, emitsonRatingChanged(k).RatingCardContent: stateless. Takes the fullRatingUiStateand lambdas. It is trivial to preview and unit test without a ViewModel.RatingCardScreen: the only stateful wrapper. It callscollectAsStateWithLifecycle()and forwards events to the ViewModel.
The ViewModel is the single source of truth. That makes rotation, testing and reuse straightforward.
Handling the edge cases
Double submission. Disabling the button is only cosmetic; two taps can land before the next recomposition. The real guard lives in the ViewModel: submit() checks canSubmit and flips to Loading inside one atomic _uiState.update {}. Only the call that performed that transition launches a coroutine. Every later call sees Loading and returns. The payload is captured from the same state snapshot, so it matches what the user saw at tap time.
Rotation. The ViewModel outlives the activity, so its state and its in-flight viewModelScope job survive. The new UI just re-collects the current state. The request starts only from a click handler, never from composition or a LaunchedEffect, so nothing is re-triggered. For process death, mirror rating and comment into SavedStateHandle.
Over-long paste. updateComment applies take(280), so the state can never hold an invalid comment. isValid still checks the length as a defensive invariant, and the counter turns red when it reaches the limit. An alternative is to accept the long text and show an error, which gives more feedback but allows an invalid state.
Other rules worth stating
- Rating is clamped to
0..maxStars; rating 0 keeps Submit disabled. - Edits are ignored while
Loading, so the visible draft always equals the submitted payload. - After an error the draft is retained, so Retry resends the same data.
reset()cancels the running job before restoring the default state, so a late success cannot overwrite the reset.CancellationExceptionis rethrown and never shown to the user.take(280)counts UTF-16 code units and can split an emoji's surrogate pair. Mention grapheme-aware truncation withBreakIteratorif it matters.
Code
const val MAX_COMMENT = 280
data class RatingUiState(
val rating: Int = 0,
val comment: String = "",
val submissionStatus: SubmissionStatus = SubmissionStatus.Idle,
val errorMessage: String? = null
) {
val isValid: Boolean get() = rating in 1..5 && comment.length <= MAX_COMMENT
val canSubmit: Boolean get() = isValid && submissionStatus !is SubmissionStatus.Loading
}
sealed interface SubmissionStatus {
object Idle : SubmissionStatus
object Loading : SubmissionStatus
object Success : SubmissionStatus
object Error : SubmissionStatus
}
interface FeedbackRepository { suspend fun submit(rating: Int, comment: String) }
class FakeFeedbackRepository : FeedbackRepository {
override suspend fun submit(rating: Int, comment: String) {
delay(1000)
if (Random.nextInt(4) == 0) throw IOException("Network error. Please try again.")
}
}
class RatingViewModel(
private val repository: FeedbackRepository = FakeFeedbackRepository()
) : ViewModel() {
private val _uiState = MutableStateFlow(RatingUiState())
val uiState: StateFlow<RatingUiState> = _uiState.asStateFlow()
private var submitJob: Job? = null
fun setRating(value: Int) = _uiState.update {
if (it.submissionStatus is SubmissionStatus.Loading) it
else it.copy(rating = value.coerceIn(0, 5))
}
fun updateComment(text: String) = _uiState.update {
if (it.submissionStatus is SubmissionStatus.Loading) it
else it.copy(comment = text.take(MAX_COMMENT))
}
fun submit() {
var snapshot: RatingUiState? = null
_uiState.update { s ->
if (s.canSubmit) {
snapshot = s
s.copy(submissionStatus = SubmissionStatus.Loading, errorMessage = null)
} else {
snapshot = null
s
}
}
val payload = snapshot ?: return
submitJob = viewModelScope.launch {
try {
repository.submit(payload.rating, payload.comment)
_uiState.update { it.copy(submissionStatus = SubmissionStatus.Success) }
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
_uiState.update {
it.copy(
submissionStatus = SubmissionStatus.Error,
errorMessage = e.message ?: "Something went wrong."
)
}
}
}
}
fun reset() {
submitJob?.cancel()
_uiState.value = RatingUiState()
}
}
@Composable
fun StarRatingBar(
rating: Int,
onRatingChanged: (Int) -> Unit,
modifier: Modifier = Modifier,
maxStars: Int = 5
) {
Row(modifier.selectableGroup()) {
for (k in 1..maxStars) {
val filled = k <= rating
Icon(
imageVector = if (filled) Icons.Filled.Star else Icons.Outlined.StarOutline,
contentDescription = "Rate $k of $maxStars",
tint = if (filled) Color(0xFFFFB300) else LocalContentColor.current,
modifier = Modifier
.size(48.dp)
.selectable(
selected = k == rating,
role = Role.RadioButton,
onClick = { onRatingChanged(k) }
)
.padding(8.dp)
)
}
}
}
@Composable
fun RatingCardScreen(
viewModel: RatingViewModel = viewModel(),
modifier: Modifier = Modifier
) {
val state by viewModel.uiState.collectAsStateWithLifecycle()
RatingCardContent(
state = state,
onRatingChanged = viewModel::setRating,
onCommentChanged = viewModel::updateComment,
onSubmit = viewModel::submit,
onReset = viewModel::reset,
modifier = modifier
)
}
RatingCardContent is a plain stateless composable. It switches on submissionStatus:
Success: shows the thank-you view with a Reset button.- Other statuses: show the star bar, the comment
OutlinedTextField, the"${comment.length}/280"counter, and the Submit button (disabled unlesscanSubmit, showing aCircularProgressIndicatorwhile loading). Error: adds a banner with the message and a Retry button that callsonSubmit.
Complexity
- Rendering the bar is O(maxStars) per recomposition, and Compose skips stars whose inputs are unchanged.
updateCommentis O(n) in the pasted length because of the truncation copy.- All other state transitions are O(1).
- Space is O(n) for the comment string and constant otherwise.
Common mistakes
- Relying on
enabled = falsealone to prevent duplicate requests. - Launching the request from
LaunchedEffector the composable body, which re-fires after rotation. - Using
rememberfor the rating or comment, so rotation loses the draft. - Letting a late success overwrite state after
reset(). - Showing
CancellationExceptionas an error message. - Exposing a
MutableStateFlowpublicly instead of a read-onlyStateFlow.