https://kotlinlang.org logo
#getting-started
Title
# getting-started
c

Colton Idle

12/03/2021, 3:06 PM
I have a behavior that I want a majority of my ViewModel classes to support. I considered creating a BaseViewModel, but I have also seen base classes that get out of control with if statements everywhere, and then it becomes clear that a base class wasn't the right approach. I have seen the statement "favor composition over inheritence", but I haven't seen a practical example of it ever (or maybe I just never connected the dots). How would I make a class have this sort of behavior be composable (not to be confused with jetpack compose) instead of using inheritence? Do I just use interfaces since I can define multiple interfaces to implement? (I know that this is sort of not necessarily kotlin, but I figured it'd be worth a shot asking here)
d

Dominaezzz

12/03/2021, 3:12 PM
I've also seen that statement but without the "favor" bit. Sometimes composition just works better since multiple inheritance is a PITA. There are several ways to compose as you can imagine, since there's no keyword for it. Use case determines how you compose I guess.
Actually I take that back about the keyword. Delegation in Kotlin (
by
) is one way to achieve composition.
a

Adam Powell

12/03/2021, 3:44 PM
start with something with a shape of
Copy code
class MyViewModel : ViewModel() {
  val myBehavior = // ???
and then iterate from there. Represent the behavior as its own final class that accepts whatever dependencies it might need
Polishing up the external interface once you have that can then start looking like what @Dominaezzz mentioned with class delegation or similar, or it might be as simple as manually declaring methods on the ViewModel that call methods on your behavior object
You might end up with factory functions to help make setting things up a bit easier, maybe something like
Copy code
fun ViewModel.createMyBehavior(...): MyBehavior = MyBehaviorImpl(...).also {
  viewModelScope.launch {
    it.runOngoingBehaviorStuff()
  }
}
c

Colton Idle

12/03/2021, 3:51 PM
Thanks. Even just knowing that
Copy code
val myBehavior = // ???
is a starting point is nice. I will iteratie on this today and this weekend to see if I can come up with something. Thank you all
d

Daniel

12/03/2021, 10:56 PM
Âlso first check if you really need common behaviour for all your view models. From my experience lots of cases where the idea was thought necessarry could be avoided altogether
2
2 Views