BaseFragment architecture for android project

Viewed 2176

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?

1 Answers

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

Related