koromiko / Tutorial

We are sample code :)
325 stars 240 forks source link

Should't the initVM be before the initView? #2

Open jacobmohl opened 6 years ago

jacobmohl commented 6 years ago

I have just read your excellent blog about a simple path to begin with MVVM and also looked at you tutorial repo here.

I where just wondering if the initialization of the view model should be before the initialization of the view. What if the initView rely on some of the closures not yet set.

https://github.com/koromiko/Tutorial/blob/b389f9e118ae47f2cda987226576091b9e696d86/MVVMPlayground/MVVMPlayground/Module/PhotoList/PhotoListViewController.swift#L28

I had some code which can so quickly that the closures (in initViewModel) where not yet set. Is there any danger in setting the closures as the first thing in viewDidLoad?

koromiko commented 6 years ago

Yes, it might cause problems like the closure is triggered before the UI is set. If the initView is replied on the closure, it's better to either explicitly assign the viewModel's value to the view, or introduce a side-effect (triggered immediately) to the closure. Though it might be better to have a clearer life cycle like calling the API at viewDidLoad, to avoid this kind of situation

My recent experiment shows the side-effect implementation, F.Y.I :)