Skip to content
Source

ViewModel and init

I came across the first article in a series of best practices for working with ViewModel. Looks very similar in style to something from Google, which got me hooked, but thankfully it's not. In it, the author says that the init section in ViewModel is not recommended for state initialization. Yes, that's what's written - don't use init for initialization ✏️. Wait, what? I got interested.

They say it seems convenient at first glance, but it has downsides. Ok, let's go through them in order.

And what do they propose? They propose rewriting simple and clear code where in the init block in viewModelScope some loading is triggered to some reactive chains like flow{...}.stateIn() and stateFlow.asLiveData().switchMap{...} in properties. Which is either questionable, or just doesn't scale to more complex ViewModels, or isn't a universal solution, i.e. in each case you need to come up with a different solution. init is beautiful because you don't have to think, you write simple (almost) synchronous code in any scenario. Just don't forget to split it into functions to make it clear, that's all.

And I don't understand why all this at all, they're working around limitations they invented themselves. There's some food for thought, of course, but neither the arguments nor the solutions convince me at all. Am I missing something or is Medium hyping nonsense again? 🤔