Android kotlin MVP class delegation
So I have the following situations:
class NowActivity: AppCompatActivity(), NowScreen, NowDelegate by NowDelegateImpl(){
onCreate(...){
presenter.attachView(this)
}
Is there any way to delegate the implementation of some nowscreen methods to nowdelegate so that you can perform the following operations in the Presenter:
view.callSomeFunc()
Callsomefund() is implemented in nowdelegate
Is there any way to accomplish such a thing? The problem is that I'm using MVP, which attaches views to the presenter. But some view implementations are repeated in some activities, so I want to delegate them to another class
resolvent:
If both interfaces implement the same object, they can be delegated to the same object. To do this, just make the object a constructor parameter, for example:
class NowActivity(delegate: NowDelegateImpl): AppCompatActivity(),
NowScreen by delegate,
NowDelegate by delegate {
constructor (): this(NowDelegateImpl()) {} // need this default constructor for Android to call
...
}
If a delegate cannot implement all the functions of two interfaces at the same time, you can make it a member, and then manually delegate some function subsets to it
class NowActivity(private val delegate: NowDelegateImpl):
AppCompatActivity(),
NowScreen,
NowDelegate by delegate {
constructor (): this(NowDelegateImpl()) {} // need this default constructor for Android to call
override fun callSomeFund() { delegate.callSomeFund() }
}
Both options require you to create a default constructor that creates an object for delegation and passes it to the main constructor
Here, it is broken down into an all inclusive example, which is not limited to Android, in case others want to see everything happen
Example 1: delegate all interfaces to the same object:
interface CommonStuff {
fun foo1()
fun foo2()
}
interface LessCommonStuff {
fun bar()
}
class CommonDelegate1: CommonStuff, LessCommonStuff {
override fun foo1() {}
override fun foo2() {}
override fun bar() {}
}
class Activity1(delegate: CommonDelegate1):
LessCommonStuff by delegate,
CommonStuff by delegate {
constructor (): this(CommonDelegate1()) {} // need this default constructor
// ...
}
Example 2: manually delegate some interfaces using members:
interface CommonStuff {
fun foo1()
fun foo2()
}
interface LessCommonStuff {
fun bar()
}
class CommonDelegate2: CommonStuff {
override fun foo1() {}
override fun foo2() {}
fun barLikeThing() {}
}
class Activity2(private val delegate: CommonDelegate2):
LessCommonStuff,
CommonStuff by delegate {
constructor (): this(CommonDelegate2()) {} // need this default constructor
override fun bar() { delegate.barLikeThing() }
}