Skip to content

Instantly share code, notes, and snippets.

@BapNesS
Created February 11, 2020 14:27
Show Gist options
  • Save BapNesS/08429d955d1afa9205a9ce1ed2115052 to your computer and use it in GitHub Desktop.
Save BapNesS/08429d955d1afa9205a9ce1ed2115052 to your computer and use it in GitHub Desktop.
Easy way to Toast with ViewModel, LiveData & a bit of abstraction. 1/4
/**
* Base for other activities
*/
abstract class BaseActivity : AppCompatActivity() {
abstract val baseViewModel: BaseViewModel?
// Get a ViewModel that is a BaseViewModel
protected inline fun <reified T : BaseViewModel> provideViewModel(): T = ViewModelProviders.of(this)[T::class.java]
/**
* When a message event is thrown, handle it and show it
*/
protected open fun initObservers() {
baseViewModel?.message?.observe(this, Observer { event ->
event.getContentIfNotHandled()?.let { message ->
// Toast the [message]
toast(message)
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment