iOS Swift Firestore and how avoid singleton

Viewed 340

I am using Google Firestore and MVVM pattern. As I know it is a good practice to avoid using singleton because of testing problems. But how should I work with Firestore correctly without it?

I am afraid that every time I create service instance in my View Model than new subscription to Firestore will be created. Also in case of MVVM, where is correct place to subscribe and unsubscribe to Firestore database? Should it happen in ViewModel or some service should handle this?

1 Answers

The idea that Singletons are anti patterns and must be avoided at any cost is overrated IMHO, you can use singletons and you can test them easily using DI and mocks.

In your case a much simpler solution is to use a singleton service to handle Firestore lifecycle.

Doing this in ViewModel will result in code duplication and does not make sens as it does not link between view and model which ViewModel job.

Related