Created
October 19, 2017 16:40
-
-
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)
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
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