Skip to content

Instantly share code, notes, and snippets.

@nukeforum
Last active October 28, 2019 12:53
Show Gist options
  • Save nukeforum/8bc40d330adb9558d2060f08ac87b0e6 to your computer and use it in GitHub Desktop.
Save nukeforum/8bc40d330adb9558d2060f08ac87b0e6 to your computer and use it in GitHub Desktop.
Presenter abstract for MVP architecture
abstract class Presenter<V> : CoroutineScope {
protected var TAG: String = javaClass.simpleName
private var view: WeakReference<V>? by Delegates.observable<WeakReference<V>?>(null) { _, _, _ ->
this.onViewChanged()
}
protected var job = Job()
override val coroutineContext: CoroutineContext
get() {
if (job.isCancelled || job.isCompleted) {
job = Job()
}
return job + Dispatchers.Main
}
protected open fun onBind() {
job.cancel()
}
protected open fun onUnbind() {}
protected open fun onViewChanged() {}
fun takeView(view: V) {
if (this.view?.get() !== view) {
this.view?.clear()
this.view = WeakReference(view)
}
this.onBind()
}
fun dropView(view: V) {
this.onUnbind()
job.cancel()
if (this.view?.get() === view) {
this.view = null
}
}
protected fun view(): V? {
if (view == null) {
Log.w("Presenter", "View is null for $TAG")
return null
} else {
return view?.get()
}
}
protected fun hasView(): Boolean {
return view() != null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment