Firebase Realtime Database
and Remote Config in Practice
Sergey Smetanin
RuBeacon
Pattern-based white-label mobile apps for order-ahead and food delivery
services. Presented as Android, iOS and Web apps.
• Complete food service use-case, from the menu display and order
creation, up to the order registration and monitoring in the restaurant
POS system.
• Integration with the most common restaurant management systems.
• Pattern-based development using Product Flavors on Android and
Targets on iOS.
FIREBASE REMOTE CONFIG
<resources>

				<string	name=«appName»>Кофе	на	вынос</string>

				<string	name="invite">Мы	ждем	Вас	в	кофейне-пекарне</string>



				<bool	name="showWalletBalance">false</bool>

				<bool	name="showDividers">true</bool>



				<integer	name="menuRepresentaUonType">0</integer>

				<integer	name="itemRepresentaUonType">3</integer>

				

				<color	name="colorPrimary">#3F51B5</color>

				<color	name="colorPrimaryDark">#303F9F</color>

				<color	name="colorAccent">#FF4081</color>



				<string-array	name="emailsList">

								<item>sismetanin@gmail.ru</item>

								<item>nikita.remnev@gmail.ru</item>

				</string-array>

				…

Configuration Problem Statement
1. Developers waste their time maintaining configuration.
2. Process of new apps launching is slow.
3. Both UI and behavior logic update requires an app update.
4. Strings localization.
Configuration Problem Solving
1. Hardcoded configuration parameters in client-side app.
• Cannot be changed without an app update.
• Cannot be changed without developers.
• Boring for developers to edit.
2. Server-side configuration parameters.
• Cannot be changed without developers.
• Client-side download, update and storage logic should be implemented.
• Server-side strings localization.
• Boring for developers to edit.
3. Firebase Remote Config.
✓Perfecto!
Firebase Remote Config Key Capabilities
• Quickly roll out changes to
your app's userbase.
• Customize your app for
segments of your user base.
• Run A/B tests to improve
your app.
FRC Parameters
FRC Conditions
FRC Conditions
Rule Type Operation(s) Value(s)
User in random percentile <=, > 0-100
OS type == iOS, Android
Device in region/country ==
Select one or more regions or
countries
App ID ==
Select from a list of App IDs for
apps associated with your
Firebase project.
App version
exactly matches, contains, does
not contain, regular expression
Enter a value to specify a specific
version of your app.
Device language == Select one or more languages.
User in audience ==
Select from a list of Firebase
Analytics audiences that you have
set up for your project.
FRС Simple Case: App Coloring
100+apps in GooglePlay
+5 new apps
per week
FRС Implementation Path
1. Add Firebase to your Android project
2. Add RC dependency to your app’s module build.gradle:
compile	'com.google.firebase:firebase-config:9.4.0'
3. Get a Remote Config object instance and sets in-app default values
from an XML file
mFirebaseRemoteConfig	=	FirebaseRemoteConfig.getInstance();

FirebaseRemoteConfigSepngs	configSepngs	=	new	FirebaseRemoteConfigSepngs.Builder()

								.setDeveloperModeEnabled(BuildConfig.DEBUG)

								.build();

mFirebaseRemoteConfig.setConfigSepngs(configSepngs);

mFirebaseRemoteConfig.setDefaults(R.xml.remote_config_defaults);
4. Fetch configuration
mFirebaseRemoteConfig.fetch(cacheExpiraUon)		//	The	default	expiraUon	duraUon	is	43200	(12	hours)	
								.addOnCompleteListener(new	OnCompleteListener<Void>()	{

												@Override

												public	void	onComplete(@NonNull	Task<Void>	task)	{

																if	(task.isSuccessful())	{

																			Log.d(TAG,	"Fetch	Succeeded");

																				//	Once	the	config	is	successfully	fetched	it	must	be	acUvated	before	newly	fetched

																				//	values	are	returned.

																				mFirebaseRemoteConfig.acUvateFetched();

																}	else	{

																				Log.d(TAG,	"Fetch	Failed");

																}

																updateColors();

												}

								});
5. Add client logic
private	void	updateColors()	{

				mToolbar.setBackgroundColor(Color.parseColor(mFirebaseRemoteConfig.getString(TOOLBAR_BACKGROUND_COLOR_KEY)));

				mToolbar.setTitleTextColor(Color.parseColor(mFirebaseRemoteConfig.getString(TOOLBAR_TITLE_TEXT_COLOR_KEY)));

				if	(Build.VERSION.SDK_INT	>=	Build.VERSION_CODES.LOLLIPOP)	{

								Window	window	=	getWindow();

								window.setStatusBarColor(Color.parseColor(mFirebaseRemoteConfig.getString(STATUS_BAR_COLOR_KEY)));

								window.setNavigaUonBarColor(Color.parseColor(mFirebaseRemoteConfig.getString(NAVIGATION_BAR_COLOR_KEY)));

				}

}
Results
1. Developers are free from configuration maintaining.
2. Account managers are able to maintain configuration by themselves.
3. UI and behavior logic can be updated without an app update.
4. Embedded approach to string localization.
5. Ready-to-start platform for A/B testing.
FIREBASE REALTIME DATABASE
Menu Replication Problem Statement
1. Menu should be the same at all stages.
2. Its common for a restaurant to update menu at least one time per week.
3. Weak point in communication between client app and RuBeacon server
due to mobile internet.
Restaurant
Management
System
Client App
RuBeacon
Server
History of Menu Replication Problem Solving
1. Synchronous downloading on splash screen.
• Bad UX due to wasting of time on the splash screen.
• Client-side storage logic should be implemented.
2. Asynchronous downloading on the splash screen.
• Lack of synchronization.
• Client-side storage logic should be implemented.
3. Async downloading & silent push.
• Client-side storage logic should be implemented.
• Silent push should be implemented on both server and client sides.
4. Firebase Realtime Database.
✓Perfecto!.
FRD Key Capabilities
• Realtime
synchronization
• Accessible from
client Devices
• Offline Capabilities
FRD Structure Your Database
1. Avoid nesting data
2. Flatten data structures
3. Create data that scales
FRD Rules
1. .write
2. .read
3. .validate
4. .indexOn
FRD Available data types
• String
• Long
• Double
• Boolean
• Map<String, Object>
• List<Object>
• Custom Java object
public	class	User	{

				public	String	username;

				public	String	email;



				public	String	getEmail()	{

								return	email;

				}



				public	String	getUsername()	{

								return	username;

				}



				public	User()	{

				}



				public	User(String	username,	String	email)	{

								this.username	=	username;

								this.email	=	email;

				}

}
FRD Save Data
1. Get an instance of database
FirebaseDatabase	database	=	FirebaseDatabase.getInstance();

DatabaseReference	myRef	=	database.getReference();
private	void	writeNewUser(String	userId,	String	name,	String	email)	{

				User	user	=	new	User(name,	email);

				mDatabase.child("users").child(userId).setValue(user);

}
2. Basic write operations
FRD Retrieve Data
1. Get an instance of database
2. Add listeners for events
Listener Event Callback
ValueEventListener onDataChange()
ChildEventListener onChildAdded()
onChildChanged()
onChildRemoved()
onChildMoved()
FRD Offline Capabilities
1. Disk persistence
DatabaseReference	scoresRef	=	FirebaseDatabase.getInstance().getReference("items");

scoresRef.keepSynced(true);
2. Keeping data fresh
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
3. Querying data offline
DatabaseReference	scoresRef	=	FirebaseDatabase.getInstance().getReference("items");

scoresRef.orderByValue().limitToLast(4).addChildEventListener(new	ChildEventListener()	{

				@Override

				public	void	onChildAdded(DataSnapshot	snapshot,	String	previousChild)	{	}

});	
//	СonnecUon	error	
scoresRef.orderByValue().limitToLast(2).addChildEventListener(new	ChildEventListener()	{

				@Override

				public	void	onChildAdded(DataSnapshot	snapshot,	String	previousChild)	{	}

});
FRD Case: Menu Synchronization
Results
1. Reducing the residence time at the splash screen for 3 seconds in
average
2. Realtime synchronization instead of request/response model
3. Embedded tools for storing, queuing, caching and updating data.
Restaurant
Management
System
FirebaseClient App
RuBeacon
Server
References
1. "Have you met the Realtime Database?", The Firebase Blog, 2016. [Online]. Available: https://
firebase.googleblog.com/2016/07/have-you-met-realtime-database.html. [Accessed: 18- Sep- 2016].
2. "Firebase Realtime Database | Firebase", Google Developers, 2016. [Online]. Available: https://
firebase.google.com/docs/database/. [Accessed: 18- Sep- 2016].
3. "Firebase Remote Config | Firebase", Google Developers, 2016. [Online]. Available: https://
firebase.google.com/docs/remote-config/. [Accessed: 18- Sep- 2016].
4. "Firebase: Now with more querying!", The Firebase Blog, 2016. [Online]. Available: https://
firebase.googleblog.com/2014/11/firebase-now-with-more-querying.html. [Accessed: 18- Sep- 2016].
5. "Queries, Part 1: Common SQL Queries Converted for Firebase", The Firebase Blog, 2016. [Online].
Available: https://firebase.googleblog.com/2013/10/queries-part-1-common-sql-queries.html.
[Accessed: 18- Sep- 2016].
6. "Queries, Part 2: Advanced Searches with Firebase, made Plug-and-Play Simple", The Firebase Blog,
2016. [Online]. Available: https://firebase.googleblog.com/2014/01/queries-part-2-advanced-
searches-with.html. [Accessed: 18- Sep- 2016].
THANK YOU FOR ATTENTION
Q&A
sismetanin@gmail.com

Firebase Realtime Database and Remote Config in Practice - DroidCon Moscow 2016

  • 2.
    Firebase Realtime Database andRemote Config in Practice Sergey Smetanin
  • 3.
    RuBeacon Pattern-based white-label mobileapps for order-ahead and food delivery services. Presented as Android, iOS and Web apps. • Complete food service use-case, from the menu display and order creation, up to the order registration and monitoring in the restaurant POS system. • Integration with the most common restaurant management systems. • Pattern-based development using Product Flavors on Android and Targets on iOS.
  • 4.
  • 6.
  • 7.
    Configuration Problem Statement 1.Developers waste their time maintaining configuration. 2. Process of new apps launching is slow. 3. Both UI and behavior logic update requires an app update. 4. Strings localization.
  • 8.
    Configuration Problem Solving 1.Hardcoded configuration parameters in client-side app. • Cannot be changed without an app update. • Cannot be changed without developers. • Boring for developers to edit. 2. Server-side configuration parameters. • Cannot be changed without developers. • Client-side download, update and storage logic should be implemented. • Server-side strings localization. • Boring for developers to edit. 3. Firebase Remote Config. ✓Perfecto!
  • 9.
    Firebase Remote ConfigKey Capabilities • Quickly roll out changes to your app's userbase. • Customize your app for segments of your user base. • Run A/B tests to improve your app.
  • 10.
  • 11.
  • 12.
    FRC Conditions Rule TypeOperation(s) Value(s) User in random percentile <=, > 0-100 OS type == iOS, Android Device in region/country == Select one or more regions or countries App ID == Select from a list of App IDs for apps associated with your Firebase project. App version exactly matches, contains, does not contain, regular expression Enter a value to specify a specific version of your app. Device language == Select one or more languages. User in audience == Select from a list of Firebase Analytics audiences that you have set up for your project.
  • 13.
    FRС Simple Case:App Coloring 100+apps in GooglePlay +5 new apps per week
  • 14.
    FRС Implementation Path 1.Add Firebase to your Android project 2. Add RC dependency to your app’s module build.gradle: compile 'com.google.firebase:firebase-config:9.4.0' 3. Get a Remote Config object instance and sets in-app default values from an XML file mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
 FirebaseRemoteConfigSepngs configSepngs = new FirebaseRemoteConfigSepngs.Builder()
 .setDeveloperModeEnabled(BuildConfig.DEBUG)
 .build();
 mFirebaseRemoteConfig.setConfigSepngs(configSepngs);
 mFirebaseRemoteConfig.setDefaults(R.xml.remote_config_defaults);
  • 15.
  • 16.
    5. Add clientlogic private void updateColors() {
 mToolbar.setBackgroundColor(Color.parseColor(mFirebaseRemoteConfig.getString(TOOLBAR_BACKGROUND_COLOR_KEY)));
 mToolbar.setTitleTextColor(Color.parseColor(mFirebaseRemoteConfig.getString(TOOLBAR_TITLE_TEXT_COLOR_KEY)));
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
 Window window = getWindow();
 window.setStatusBarColor(Color.parseColor(mFirebaseRemoteConfig.getString(STATUS_BAR_COLOR_KEY)));
 window.setNavigaUonBarColor(Color.parseColor(mFirebaseRemoteConfig.getString(NAVIGATION_BAR_COLOR_KEY)));
 }
 }
  • 18.
    Results 1. Developers arefree from configuration maintaining. 2. Account managers are able to maintain configuration by themselves. 3. UI and behavior logic can be updated without an app update. 4. Embedded approach to string localization. 5. Ready-to-start platform for A/B testing.
  • 19.
  • 20.
    Menu Replication ProblemStatement 1. Menu should be the same at all stages. 2. Its common for a restaurant to update menu at least one time per week. 3. Weak point in communication between client app and RuBeacon server due to mobile internet. Restaurant Management System Client App RuBeacon Server
  • 21.
    History of MenuReplication Problem Solving 1. Synchronous downloading on splash screen. • Bad UX due to wasting of time on the splash screen. • Client-side storage logic should be implemented. 2. Asynchronous downloading on the splash screen. • Lack of synchronization. • Client-side storage logic should be implemented. 3. Async downloading & silent push. • Client-side storage logic should be implemented. • Silent push should be implemented on both server and client sides. 4. Firebase Realtime Database. ✓Perfecto!.
  • 22.
    FRD Key Capabilities •Realtime synchronization • Accessible from client Devices • Offline Capabilities
  • 23.
    FRD Structure YourDatabase 1. Avoid nesting data 2. Flatten data structures 3. Create data that scales FRD Rules 1. .write 2. .read 3. .validate 4. .indexOn
  • 24.
    FRD Available datatypes • String • Long • Double • Boolean • Map<String, Object> • List<Object> • Custom Java object public class User {
 public String username;
 public String email;
 
 public String getEmail() {
 return email;
 }
 
 public String getUsername() {
 return username;
 }
 
 public User() {
 }
 
 public User(String username, String email) {
 this.username = username;
 this.email = email;
 }
 }
  • 25.
    FRD Save Data 1.Get an instance of database FirebaseDatabase database = FirebaseDatabase.getInstance();
 DatabaseReference myRef = database.getReference(); private void writeNewUser(String userId, String name, String email) {
 User user = new User(name, email);
 mDatabase.child("users").child(userId).setValue(user);
 } 2. Basic write operations
  • 26.
    FRD Retrieve Data 1.Get an instance of database 2. Add listeners for events Listener Event Callback ValueEventListener onDataChange() ChildEventListener onChildAdded() onChildChanged() onChildRemoved() onChildMoved()
  • 27.
    FRD Offline Capabilities 1.Disk persistence DatabaseReference scoresRef = FirebaseDatabase.getInstance().getReference("items");
 scoresRef.keepSynced(true); 2. Keeping data fresh FirebaseDatabase.getInstance().setPersistenceEnabled(true); 3. Querying data offline DatabaseReference scoresRef = FirebaseDatabase.getInstance().getReference("items");
 scoresRef.orderByValue().limitToLast(4).addChildEventListener(new ChildEventListener() {
 @Override
 public void onChildAdded(DataSnapshot snapshot, String previousChild) { }
 }); // СonnecUon error scoresRef.orderByValue().limitToLast(2).addChildEventListener(new ChildEventListener() {
 @Override
 public void onChildAdded(DataSnapshot snapshot, String previousChild) { }
 });
  • 28.
    FRD Case: MenuSynchronization
  • 31.
    Results 1. Reducing theresidence time at the splash screen for 3 seconds in average 2. Realtime synchronization instead of request/response model 3. Embedded tools for storing, queuing, caching and updating data. Restaurant Management System FirebaseClient App RuBeacon Server
  • 32.
    References 1. "Have youmet the Realtime Database?", The Firebase Blog, 2016. [Online]. Available: https:// firebase.googleblog.com/2016/07/have-you-met-realtime-database.html. [Accessed: 18- Sep- 2016]. 2. "Firebase Realtime Database | Firebase", Google Developers, 2016. [Online]. Available: https:// firebase.google.com/docs/database/. [Accessed: 18- Sep- 2016]. 3. "Firebase Remote Config | Firebase", Google Developers, 2016. [Online]. Available: https:// firebase.google.com/docs/remote-config/. [Accessed: 18- Sep- 2016]. 4. "Firebase: Now with more querying!", The Firebase Blog, 2016. [Online]. Available: https:// firebase.googleblog.com/2014/11/firebase-now-with-more-querying.html. [Accessed: 18- Sep- 2016]. 5. "Queries, Part 1: Common SQL Queries Converted for Firebase", The Firebase Blog, 2016. [Online]. Available: https://firebase.googleblog.com/2013/10/queries-part-1-common-sql-queries.html. [Accessed: 18- Sep- 2016]. 6. "Queries, Part 2: Advanced Searches with Firebase, made Plug-and-Play Simple", The Firebase Blog, 2016. [Online]. Available: https://firebase.googleblog.com/2014/01/queries-part-2-advanced- searches-with.html. [Accessed: 18- Sep- 2016].
  • 33.
    THANK YOU FORATTENTION Q&A sismetanin@gmail.com