-
-
Save weverb2/f92e276c55c24c8f63214cf736aac911 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@AndroidEntryPoint | |
class MainActivity : ComponentActivity() { | |
private val viewModel: FormValidationViewModel by viewModels() | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContent { | |
val emailState by viewModel.emailAddress.observeAsState() | |
val isFormValid by viewModel.valid.observeAsState() | |
MaterialTheme { | |
MyCoolForm( | |
emailText = emailState ?: "", | |
onEmailChanged = { viewModel.emailAddress.postValue(it) }, | |
isFormValid = isFormValid ?: false | |
) | |
} | |
} | |
} | |
} | |
@Composable | |
fun MyCoolForm( | |
emailText: String = "", | |
onEmailChanged: (String) -> Unit = {}, | |
isFormValid: Boolean = false | |
) { | |
Column( | |
horizontalAlignment = Alignment.CenterHorizontally, | |
modifier = Modifier | |
.fillMaxSize() | |
.padding(16.dp) | |
) { | |
OutlinedTextField( | |
value = emailText, | |
label = { Text("Email") }, | |
onValueChange = onEmailChanged, | |
modifier = Modifier.fillMaxWidth() | |
) | |
Spacer(modifier = Modifier.size(4.dp)) | |
Button(enabled = isFormValid, onClick = {}) { | |
Text(text = "Save") | |
} | |
} | |
} | |
@HiltViewModel | |
class FormValidationViewModel @Inject constructor() : ViewModel() { | |
val emailAddress = MutableLiveData<String>("") | |
val valid = MediatorLiveData<Boolean>().apply { | |
addSource(emailAddress) { | |
val valid = isFormValid(it) | |
Log.d(it, valid.toString()) | |
value = valid | |
} | |
} | |
fun isFormValid(emailAddress: String): Boolean { | |
return Patterns.EMAIL_ADDRESS.matcher(emailAddress).matches() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment