Skip to content

Instantly share code, notes, and snippets.

@cjbrooks12
Last active February 3, 2020 20:19
Show Gist options
  • Save cjbrooks12/d9ebbd7fe701de5ea6bbb0f447a5165c to your computer and use it in GitHub Desktop.
Save cjbrooks12/d9ebbd7fe701de5ea6bbb0f447a5165c to your computer and use it in GitHub Desktop.
Lasagna Screens
class LoginActivity : AppCompatActivity(), LoginView {
val vm: LoginViewModel by lazy {
LoginViewModel(this, LoginService.getInstance(BuildConfig.DEBUG))
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
screen_header.setText("Login Screen")
login_form_username.addTextChangedListener(AbstractTextWatcher { vm.username = it })
login_form_password.addTextChangedListener(AbstractTextWatcher { vm.password = it })
login_form_submit_button.setOnClickListener {
vm.attemptLogin()
}
}
override fun onLoginSuccessful() {
startActivity(Intent(this, HomeActivity::class.java))
}
override fun setButtonEnabled(enabled: Boolean) {
login_form_submit_button.isEnabled = enabled
}
}
interface LoginService {
fun login(username: String, password: String, onLoggedIn: () -> Unit)
companion object {
fun getInstance(debug: Boolean): LoginService {
return if (debug) DebugLoginService() else ProductionLoginService(LoginApi())
}
}
}
class ProductionLoginService(private val loginApi: LoginApi) : LoginService {
override fun login(username: String, password: String, onLoggedIn: () -> Unit) {}
}
class DebugLoginService : LoginService {
override fun login(username: String, password: String, onLoggedIn: () -> Unit) {}
}
interface LoginView {
fun onLoginSuccessful()
fun setButtonEnabled(enabled: Boolean)
}
class LoginViewModel(
private val view: LoginView,
private val loginService: LoginService
) {
var username: String? = null
set(value) {
field = value
onFieldsChanged()
}
var password: String? = null
set(value) {
field = value
onFieldsChanged()
}
fun attemptLogin() {
loginService.login(username!!, password!!) {
view.onLoginSuccessful()
}
}
private fun onFieldsChanged() {
view.setButtonEnabled(username != null && password != null)
}
}
class AbstractTextWatcher(
val onTextChanged: (String)->Unit
) : TextWatcher {
override fun afterTextChanged(s: Editable?) {}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
onTextChanged(s.toString())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment