Created
February 11, 2020 14:28
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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