Home > Software engineering >  Android Room and Firebase in a MVVM Architecture - Offline First Application
Android Room and Firebase in a MVVM Architecture - Offline First Application

Time:11-20

Can Android Room Database be used as an (offline/local data source) and Firebase Database as the (online data source) in an MVVM repository (gluing the data together) refer to the figure below. Having the same database table and column setup. The application can be used and make changes offline and later sync the modified version on firebase when the internet is available.

Figure 1: MVVM ROOM FIREBASE FIGURE
Figure 2: Data Layer on Repository

Problem: I already have a room database following MVVM architecture but can't figure out how to integrate firebase as my online data source and synch to tables.

Knowing: Android's Room database is a SQL database, while Firebase's Realtime Database is a NoSQL database.

If this is possible, how firebase can be set on as an online data source connected to the repository in a simplified version or an article I can follow? Or is there an alternative wherein, a database is suggested instead?

CodePudding user response:

Can Android Room Database be used as an (offline/local data source) and Firebase Database as the (online data source) in an MVVM repository?

For sure it can be, but I cannot see any reason why you would do that. Why? Because the Realtime Database has its own offline persistence mechanism. This means that your application will continue to work even if the user device temporarily loses its network connection. Besides that, all the cached data is available while the device is offline and Firebase resends any writes when the internet connectivity is restored.

The application can be used and make changes offline and later sync the modified version on firebase when the internet is available.

You're describing exactly how the Realtime Database works if you enable disk persistence using the following line of code.

FirebaseDatabase.instance.setPersistenceEnabled(true);

If this is possible, how firebase can be set on as an online data source connected to the repository in a simplified version or an article I can follow? Or is there an alternative wherein, a database is suggested instead?

I don't see why would you add an extra level of complexity when the Realtime Database already handles that for you. However, if you still want to do that, then you have to check inside the ViewModel class if the device is connected to the internet or not. And according to the connection state, you should request the data either from the Realtime Database or from Room.

Here are some useful links:

If you consider at some point in time try using Cloud Firestore, then I also recommend you read the following resource:

Remember, that in Cloud Firestore, for Android and Apple platforms, offline persistence is enabled by default.

  • Related