Skip to content

Instantly share code, notes, and snippets.

@BapNesS
Created February 11, 2020 14:28
Show Gist options
  • Save BapNesS/3125b3f2aa6317a7486ee9c11fdc4017 to your computer and use it in GitHub Desktop.
Save BapNesS/3125b3f2aa6317a7486ee9c11fdc4017 to your computer and use it in GitHub Desktop.
Easy way to Toast with ViewModel, LiveData & a bit of abstraction. 3/4
class UsableActivity : BaseActivity() {
private lateinit var viewModel: UsableViewModel
override val baseViewModel: BaseViewModel?
get() = viewModel
// DataBinding stuff
private lateinit var binding: ActivityUsableBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// DataBinding stuff
binding = DataBindingUtil.setContentView(this@UsableActivity, R.layout.activity_usable)
initViewModelAndBinding {
// Do other stuff if needed
}
}
/**
* Do multiple things:
* - Initialize the current [viewModel] ViewModel
* - Do the binding
* - Initialize the [viewModel] observers
*/
private fun initViewModelAndBinding(after: () -> Unit ) {
viewModel = provideViewModel()
binding.viewModel = viewModel
binding.lifecycleOwner = this
binding.executePendingBindings()
initObservers()
after()
}
/**
* Should be done after [baseViewModel] instantiation
*/
override fun initObservers() {
// Important : don't forget to call the super method
super.initObservers()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment