Skip to content

Instantly share code, notes, and snippets.

@scottroemeschke
Created October 19, 2017 16:40
Show Gist options
  • Save scottroemeschke/c9d4523c224da1113891a0b4aff55353 to your computer and use it in GitHub Desktop.
Save scottroemeschke/c9d4523c224da1113891a0b4aff55353 to your computer and use it in GitHub Desktop.
Just an example of handling view null checks in presenter in a low boilerplate, functional style with Kotlin (inline functions, extension functions, lambda arguments, etc)
interface Presenter<V> {
fun getView(): V
fun attachView(view: V)
fun detachView()
}
/*
Functional style of handling view null-checking/handling
Functions apply methods on the view, or pass view as argument to functions.
There is "do-nothing" if view is detached, throw exception if view is detached, and
"do-something" (like analytics, or logging, etc.) if view is detached
*/
inline fun <V> Presenter<V>.onView(opOnView: V.() -> Unit) {
getView()?.opOnView()
}
inline fun <V> Presenter<V>.onViewOrThrow(opOnView: V.() -> Unit, errorMsg: String? = null) {
getView()?.opOnView() ?: throw Exception(errorMsg ?: "view is not attached")
}
inline fun <V> Presenter<V>.onView(opOnView: V.() -> Unit, actionWhenViewDetached: () -> Unit) {
val view = getView()
when (view) {
null -> actionWhenViewDetached()
else -> view.opOnView()
}
}
inline fun <V> Presenter<V>.withView(withViewOp: (V) -> Unit) {
val view = getView()
if (view != null) withViewOp(view)
}
inline fun <V> Presenter<V>.withView(withViewOp: (V) -> Unit, actionWhenViewDetached: () -> Unit) {
val view = getView()
when (view) {
null -> actionWhenViewDetached()
else -> withViewOp(view)
}
}
inline fun <V> Presenter<V>.withViewOrThrow(withViewOp: (V) -> Unit, errorMsg: String? = null) {
val view = getView()
when (view) {
null -> throw Exception(errorMsg ?: "view is not attached")
else -> withViewOp(view)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment