Simplify Android ViewModels by using these Kotlin extensions (part 1)
My English is not perfect, So I’m going to keep story short and start immediately.
The ViewModel
has it’s own CoroutineScope
(viewModelScope), which is bounded to ViewModels lifecycle. By using this coroutineScope We can extend ViewModels to have more simpler and readable codes.
Normally We’re launching new coroutines directly on viewModelScope:
The above code has no problem, But by using the following extensions, we can prevent the repetition of viewModelScope
and have a simpler and much more readable code.
The result is pretty simple. If you’re going to use onMainImmediate
extension, make sure to read documentation about the Dispatcher.Main.Immediate.
It can throw exception in some Conditions.
My offer is to use
Dispatcher.Main
instead, it’s safe!
The result is pretty simple.
I’m working on next part which is contain some more extensions and tricks to simplify ViewModels.