Skip to content

Instantly share code, notes, and snippets.

@harryhan24
Forked from deividasstr/BaseFragment.kt
Created September 25, 2018 20:01
Show Gist options
  • Select an option

  • Save harryhan24/6a0a36871bfc6b6b666edc165ab50172 to your computer and use it in GitHub Desktop.

Select an option

Save harryhan24/6a0a36871bfc6b6b666edc165ab50172 to your computer and use it in GitHub Desktop.
abstract class BaseFragment<VB : ViewDataBinding, VM : BaseViewModel> : DaggerFragment() {
abstract fun getViewModelClass(): Class<VM>
abstract fun layoutId(): Int
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
protected lateinit var binding: VB
protected lateinit var viewModel: VM
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProviders.of(this, viewModelFactory)[getViewModelClass()]
observe(viewModel.errorMessage) { it ->
it.getContentIfNotHandled()?.let {
(activity as BaseActivity).alert(it.messageStringRes)
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val view = inflater.inflate(layoutId(), container, false)
binding = DataBindingUtil.bind(view)!!
binding.setLifecycleOwner(this)
return view
}
fun navController() = findNavController(view!!)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment