Snippets

Oleg Chulakov Studio Grok & Mock

Created by Владимир Самсонов last modified
class ViewModelHolder {
    enum class ViewModelBringer(var isDemo: Boolean) {
        DEMO_VIEW_MODEL_BRINGER(true) {
            override fun <T : ViewModel> getViewModel(fragment: Fragment, modelClass: Class<T>): T {
                val name = modelClass.name
                val mockName =
                    "${name.substringBeforeLast(".")}.Mock${name.substringAfterLast(".")}"
                try {
                    val modelDemoClass = Class.forName(mockName) as Class<out T>
                    return ViewModelProviders.of(fragment).get(modelDemoClass)
                } catch (e: ClassNotFoundException) {
                    return ViewModelProviders.of(fragment).get(modelClass)
                }
            }

        },
        VIEW_MODEL_BRINGER(false) {
            override fun <T : ViewModel> getViewModel(fragment: Fragment, modelClass: Class<T>): T {
                return ViewModelProviders.of(fragment).get(modelClass)
            }
        };

        abstract fun <T : ViewModel> getViewModel(fragment: Fragment, modelClass: Class<T>): T
    }

    companion object {
        fun <T : ViewModel> getViewModel(fragment: Fragment, modelClass: Class<T>): T {
            return getInstance(BuildConfig.IS_DEMO).getViewModel(fragment, modelClass)
        }

        private fun getInstance(isDemo: Boolean): ViewModelBringer {
            if (isDemo) return ViewModelBringer.DEMO_VIEW_MODEL_BRINGER
            else return ViewModelBringer.VIEW_MODEL_BRINGER
        }
    }
}
1
2
3
4
5
android {
    ...
    buildConfigField "boolean", "IS_DEMO", "true"
    ...
}

Comments (0)