Skip to content

Instantly share code, notes, and snippets.

@weverb2
Created September 12, 2021 20:10
Show Gist options
  • Save weverb2/f92e276c55c24c8f63214cf736aac911 to your computer and use it in GitHub Desktop.
Save weverb2/f92e276c55c24c8f63214cf736aac911 to your computer and use it in GitHub Desktop.
@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