How think about Kotlin.run ?
ParkYoungJin0303 opened this issue · comments
How think about Kotlin.run ?
If you use kotlin.run, you get clean code. (maybe)
override fun observeViewModel() {
val lifeCycleOwner = this@LoginActivity
viewModel.run {
showLoadingDialogEvent.observe(lifeCycleOwner, Observer { LoadingDialog.show(supportFragmentManager) })
hideLoadingDialogEvent.observe(lifeCycleOwner, Observer { LoadingDialog.hide() })
intentMainActivityEvent.observe(lifeCycleOwner, Observer {
Intent(lifeCycleOwner, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(this)
}
})
hideKeyboardEvent.observe(lifeCycleOwner, Observer {
(getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(et_login_password.windowToken, 0)
})
toastEvent.observe(lifeCycleOwner, Observer { toast(it) })
loginLogEvent.observe(lifeCycleOwner, Observer { Analytics.logEvent(lifeCycleOwner, Analytics.LOGIN, it) })
}
}
백문이 불여일견 제가 직접 변경해보았습니다.
val `this` = this@SignUpActivity
viewModel.run {
showLoadingDialogEvent.observe(`this`, Observer { LoadingDialog.show(supportFragmentManager) })
hideLoadingDialogEvent.observe(`this`, Observer { LoadingDialog.hide() })
finishActivityEvent.observe(`this`, Observer { finish() })
toastEvent.observe(`this`, Observer { toast(it) })
signUpLogEvent.observe(`this`, Observer { Analytics.logEvent(`this`, Analytics.SIGN_UP, it) })
}
위 코드에서 볼 수 있듯이 Analytics.logEvent 에는 context가 들어가지만 this@SignUpActivity를 통해 Context를 넘겨줄 수 있습니다.
그래서 lifeCycleOwner로만 this가 사용되지 않는 사실을 확인할 수 있습니다.
하지만 this라는 이름의 변수는 선언할 수 없습니다.
그래서 다양한 이름 중 `this`로 결정했습니다.
` ` 로 감싸주면 기본 신택스도 변수이름으로 사용할 수 있습니다.
실제로 적용해보니 생각보다 느낌있네요.
그래서 모두 변경하려고 합니다.
감사합니다