5

I am starting on a new project and I will be working in a team of 10 developers. I am setting up the base structure for our Android app. As I am working with a team and I want everyone to follow the same structure i.e creating ViewModel for each fragment and use data binding. How can I make it strict so that developers get an error if they don't create ViewModel for their Fragment?

So I have created the below BaseFragment:

abstract class BaseFragment<out VM : BaseViewModel, DB : ViewDataBinding> : Fragment() {

    open lateinit var binding: DB

    private fun init(inflater: LayoutInflater, container: ViewGroup?) {
        binding = DataBindingUtil.inflate(inflater, getLayoutRes(), container, false)
    }

    @LayoutRes
    abstract fun getLayoutRes(): Int

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View {
        init(inflater, container)
        super.onCreateView(inflater, container, savedInstanceState)
        return binding.root
    }

    open fun refresh() {}
}

How can I improve it more?

RKRK
  • 1,284
  • 5
  • 14
  • 18
sagar suri
  • 4,351
  • 12
  • 59
  • 122
  • 1
    I would also add mandatory super call to `onCreateView()` using `@CallSuper` so they stick to not override base behavior. – Nikola Despotoski Jun 25 '19 at 22:51
  • Any specific implementation you have @NikolaDespotoski ? – sagar suri Jun 30 '19 at 06:05
  • 2
    There is no guarantee that 1 Fragment will use 1 specific ViewModel. Sometimes you don't need ViewModel and sometimes you need 2+. Adding it as a template to the fragment itself is a mistake that leads to coupled code and will cause problems later on. – EpicPandaForce Oct 02 '19 at 16:47

1 Answers1

-1

One of the possible ways to improve your base fragment is to use reified like this:

protected inline fun <reified T : ViewModel> getViewModel(): T =
        ViewModelProviders.of(this)[T::class.java]

and call is:

private val loginViewModel: LoginViewModel = getViewModel()

Useful links on this approach:http://www.albertgao.xyz/2018/05/22/3-ways-to-handle-view-model-creation-in-android-with-dagger-and-kotlin/

How does the reified keyword in Kotlin work?

https://proandroiddev.com/how-reified-type-makes-kotlin-so-much-better-7ae539ed0304

Autumn_Cat
  • 790
  • 1
  • 14
  • 28
  • With this approach, you lose the ability to use `ViewModelProvider.Factory`. I'm sure you can improve it with some optional method parameters and default values. – EpicPandaForce Oct 02 '19 at 16:45