Home:ALL Converter>Dependency Injection for access to current User

Dependency Injection for access to current User

Ask Time:2017-08-06T15:16:42         Author:

Json Formatter

I'm trying to level up as a developer, and am currently building an app using RxSwift with MVVM. Most of my view models need access to the current user object. In just about every view controller, before I do anything, I have to fetch info for current user from database, and only then, can all other code be executed ( because so much of the logic depends on the state of the User). This also means most code is at least nested one level since fetching user is async. I actually input User into initializer of view model. There must be a better way to persist the current user throughout app. Ive recall reading a bit about dependency injection and how it allows data to be passed along as dependencies to other objects. Is this a scenario where injection could be a viable solution? Im open to other suggestions as well!

Potential solutions I've thought of since time of post

  • just pass along User through segues and assign to currentUser property in each view controller

  • after login, create a shared observable of type Observable<User> in RootViewController, and subscribe to it wherever need be. But i'd still have to put code into subscription block wherever i subscribe.

Author:,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/45529566/dependency-injection-for-access-to-current-user
yy