Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions app/src/main/java/com/example/theloop/OnboardingViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,14 @@ class OnboardingViewModel @Inject constructor(
_name.value = newName
}

fun saveName() {
viewModelScope.launch {
userPreferencesRepository.saveUserName(name.value)
fun saveName(): Boolean {
val isNameValid = name.value.isNotBlank()
if (isNameValid) {
viewModelScope.launch {
userPreferencesRepository.saveUserName(name.value)
}
}
return isNameValid
}

fun completeOnboarding() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,9 @@ fun OnboardingScreen(
Button(onClick = {
if (currentStep == 0) {
// Save Name
if (name.isNotEmpty()) {
viewModel.saveName()
if (!viewModel.saveName()) {
Toast.makeText(context, "Name cannot be blank", Toast.LENGTH_SHORT).show()
return@Button
}
Comment on lines +101 to 104
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

This imperative approach to validation has a couple of drawbacks:

  • Hardcoded String: The error message "Name cannot be blank" is hardcoded. It should be extracted to a string resource for maintainability and internationalization.
  • Poor User Experience: A Toast message is transient and disappears quickly. It's better to display a persistent error message near the input field itself.

A better approach would be to make this UI state-driven. The ViewModel could expose an error state, and the OutlinedTextField in WelcomeStep could use its isError and supportingText properties to display the validation error. This provides a much better user experience and follows modern Android development patterns.

For example, your ViewModel could manage state like this:

// In ViewModel
fun validateAndSaveName() {
    if (name.value.isBlank()) {
        // Update a UiState object with an error message/ID
    } else {
        // Clear error and launch save coroutine
    }
}

}

Expand Down