Simplify Android ViewModels by using these Kotlin extensions (part 1)

Dariush Fat'hi
1 min readMar 28, 2021

--

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 viewModelScopeand 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.

part2

--

--

Dariush Fat'hi
Dariush Fat'hi

Written by Dariush Fat'hi

Android Developer working at Mabna DP

Responses (4)