Skip to content

Instantly share code, notes, and snippets.

@hector6872
Last active November 16, 2017 09:31
Show Gist options
  • Save hector6872/9ef380a75fe91381c60c91a4642d400c to your computer and use it in GitHub Desktop.
Save hector6872/9ef380a75fe91381c60c91a4642d400c to your computer and use it in GitHub Desktop.
MVP Kotlin
abstract class BaseActivity<MODEL : BaseModel<Bundle>, VIEW : BaseView, out PRESENTER : BasePresenter<MODEL, VIEW>> : KoinActivity() {
protected abstract val presenter: PRESENTER
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val arguments = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments
val model = Class.forName(arguments.first().javaClass.toString().split(" ").last()).newInstance()
presenter.bind(model as MODEL, this as VIEW)
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
presenter.viewReady(first = savedInstanceState == null)
}
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
presenter.model.save(outState)
}
override fun onDestroy() {
super.onDestroy()
presenter.unbind()
}
}
open class BaseModel<in TYPE> {
open fun load(from: TYPE?) {}
open fun save(to: TYPE?) {}
}
abstract class BasePresenter<MODEL : BaseModel<*>, VIEW : BaseView> {
private var _view: VIEW? = null
private var _model: MODEL = BaseModel<Any>() as MODEL
val view
get() = _view
val model
get() = _model
open fun bind(model: MODEL, view: VIEW) {
this._view = view
this._model = model
}
open fun viewReady(first: Boolean = true) {}
open fun unbind() {
_view = null
}
}
abstract class BaseStatelessActivity<VIEW : BaseView, out PRESENTER : BaseStatelessPresenter<VIEW>> : AppCompatActivity() {
protected abstract val presenter: PRESENTER
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
presenter.bind(this as VIEW)
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
presenter.viewReady(first = savedInstanceState == null)
}
override fun onDestroy() {
super.onDestroy()
presenter.unbind()
}
}
abstract class BaseStatelessPresenter<VIEW : BaseView> {
private var _view: VIEW? = null
val view
get() = _view
open fun bind(view: VIEW) {
this._view = view
}
open fun viewReady(first: Boolean = true) {}
open fun unbind() {
_view = null
}
}
interface BaseView
class MainActivityPresenter : BasePresenter<MainActivityModel, MainActivityPresenter.Contract>() {
interface Contract : BaseView {
}
}
class MainActivityView : BaseActivity<MainActivityModel, MainActivityPresenter.Contract, MainActivityPresenter>(), MainActivityPresenter.Contract {
override val presenter = MainActivityPresenter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment