-
-
Save nukeforum/8bc40d330adb9558d2060f08ac87b0e6 to your computer and use it in GitHub Desktop.
Presenter abstract for MVP architecture
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
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