SlideShare une entreprise Scribd logo
1  sur  47
Building an Android app with
Jetpack Compose and Firebase
Marina Coelho
Developer Relations Engineer
@coelho_dev
Firebase
Authentication
Firebase and
Compose overview
App architecture
Calling async Firebase
methods
Firestore
Firebase
Authentication
Firebase and
Compose overview
App architecture
Calling async Firebase
methods
Firestore
Drive user engagement
Analytics
Cloud
Messaging
Remote
Config
A/B Testing
Dynamic
Links
In-app
Messaging
Improve app quality
Crashlytics
Performance
Monitoring
Test Lab
App Distribution
Build better apps
Auth
Cloud
Functions
Cloud
Firestore
Hosting
Firebase ML
Realtime
Database
Cloud
Storage
Extensions
Jetpack Compose
● Android’s modern toolkit for building native UI
● Intuitive and requires less code than writing .xml files
● First stable version of Compose was launched in 2021
Jetpack Compose
@Composable
fun Hello() {
Column(modifier = Modifier.padding(16.dp)) {
var name by remember { mutableStateOf(“”) }
if (name.isNotEmpty()) {
Text(text = "Hello, $name!")
}
}
}
Firebase
Authentication
Firebase and
Compose overview
App architecture
Calling async Firebase
methods
Firestore
Make it So
● Create and edit to-do items
● Add flags
● Add priority
● Add due date
● Mark as complete
Model-View-ViewModel
Model-View-ViewModel + Compose
How it used to be
private lateinit var auth: FirebaseAuth
public override fun onCreate() {
super.onCreate()
auth = Firebase.auth
}
public override fun onStart() {
super.onStart()
val currentUser = auth.currentUser
}
How it is now
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent { FirstComposableFunction() }
}
}
How it is now
class AccountServiceImpl() : AccountService {
override fun getUser(): FirebaseUser? {
return Firebase.auth.currentUser
}
}
Firebase
Authentication
Firebase and
Compose overview
App architecture
Calling async Firebase
methods
Firestore
Synchronous and Asynchronous methods
● Synchronous
○ Returns directly to the caller
○ Blocks the caller thread
● Asynchronous
○ Processing in another thread
○ Return to caller thread once it’s completed
How callback works
fun authenticate(
email: String,
password: String,
onResult: (Throwable?) -> Unit
) {
Firebase.auth.signInWithEmailAndPassword(email,password)
.addOnCompleteListener { onResult(it.exception) }
}
Firebase
Authentication
Firebase and
Compose overview
App architecture
Calling async Firebase
methods
Firestore
Authentication
● Knowing a user's identity allows your app to do many things
○ Securely save user data in the cloud
○ Provide the same personalized experience across all devices
● Firebase Authentication provides backend services, SDKs and UI libraries
● It supports different authentication methods
● Offers Anonymous Authentication
Authentication flow
Enabling it on the console
Enabling it on the console
Enabling it on the console
Adding to code
Add to app/build.gradle file:
dependencies {
implementation 'com.google.firebase:firebase-auth-ktx'
}
Sync Android project with Gradle files again
Providing the ViewModel
@HiltViewModel
class LoginViewModel @Inject constructor() : ViewModel() {
var uiState = mutableStateOf(LoginUiState())
private set
}
The Screen
@Composable
fun LoginScreen(
[...],
viewModel: LoginViewModel = hiltViewModel()
) {
val uiState by viewModel.uiState
}
The UI State
data class LoginUiState(
val email: String = "",
val password: String = ""
)
The Screen
OutlinedTextField(
singleLine = true,
modifier = Modifier.fillMaxWidth(),
value = uiState.email,
onValueChange = { viewModel.onEmailChange(it) },
placeholder = { Text(stringResource(R.String.email)) },
)
The Screen
Button(
onClick = { viewModel.onSignInClick() },
Modifier = Modifier.fillMaxWidth()
) {
Text(text = stringResource(R.String.sign_in))
}
The ViewModel
fun onSignInClick() {
viewModelScope.launch(exceptionHandler) {
accountService.authenticate(email, password) { error ->
if (error == null) {
linkWithEmail()
} else onError(error)
}
}
}
Firebase
Authentication
Firebase and
Compose overview
App architecture
Calling async Firebase
methods
Firestore
Cloud Firestore
● NoSQL document database in the Cloud
● Data is stored into structures called documents
● Retrieve individual or list of documents
● Listen to changes across client apps
● Offers offline support
What a document looks like in Make it So
Mapping data
data class Task(
val id: String = “”,
val title: String = "",
val priority: String = "",
val dueDate: String = "",
val dueTime: String = "",
val description: String = "",
val url: String = "",
val flag: Boolean = false,
val completed: Boolean = false,
val userId: String = ""
)
val task = result.toObject<Task>()
Enabling it on the console
Adding to code
Add to app/build.gradle file:
dependencies {
implementation 'com.google.firebase:firebase-firestore-ktx'
}
Sync Android project with Gradle files again
The service
val query = Firebase.firestore
.collection(TASK_COLLECTION)
.whereEqualTo(USER_ID, userId)
query.addSnapshotListener { value, _ ->
value?.documentChanges?.forEach {
val wasDocumentDeleted = it.type == REMOVED
onDocumentEvent(
wasDocumentDeleted, it.document.toObject<Task>()
)
}
}
The ViewModel
private fun onDocumentEvent(wasDocumentDeleted: Boolean, task: Task) {
if (wasDocumentDeleted) tasks.remove(task)
else updateTaskInList(task)
}
private fun updateTaskInList(task: Task) {
val index = tasks.indexOfFirst { it.id == task.id }
if (index < 0) tasks.add(task) else tasks[index] = task
}
var tasks = mutableStateListOf<Task>()
private set
The Screen
val tasks = viewModel.tasks
LazyColumn {
items(tasks, key = { it.id }) { taskItem ->
TaskItem(
task = taskItem,
onCheckChange = { viewModel.onTaskCheckChange(taskItem) },
onActionClick = { action ->
viewModel.onTaskActionClick(openScreen, taskItem, action)
}
)
}
}
There's a lot more in Firestore!
fun addListener(
userId: String,
onDocumentEvent: (Boolean, Task) -> Unit,
onError: (Throwable) -> Unit
)
fun removeListener()
fun getTask(taskId: String, onError: (Throwable) -> Unit, onSuccess: (Task) -> Unit)
fun saveTask(task: Task, onResult: (Throwable?) -> Unit)
fun deleteTask(taskId: String, onResult: (Throwable?) -> Unit)
fun deleteAllForUser(userId: String, onResult: (Throwable?) -> Unit)
Firebase
Authentication
Firebase and
Compose overview
App architecture
Calling async Firebase
methods
Firestore
Make it So Series
Github @coelho_dev
Blog
Thank you!

Contenu connexe

Tendances

Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Expressjguerrero999
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events WebStackAcademy
 
A Brief Introduction to React.js
A Brief Introduction to React.jsA Brief Introduction to React.js
A Brief Introduction to React.jsDoug Neiner
 
Angular - Chapter 5 - Directives
 Angular - Chapter 5 - Directives Angular - Chapter 5 - Directives
Angular - Chapter 5 - DirectivesWebStackAcademy
 
File upload using multer in node.js and express.js [2021 tutorial]
File upload using multer in node.js and express.js [2021 tutorial]File upload using multer in node.js and express.js [2021 tutorial]
File upload using multer in node.js and express.js [2021 tutorial]Katy Slemon
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesHùng Nguyễn Huy
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxMalla Reddy University
 
Introduction To Angular's reactive forms
Introduction To Angular's reactive formsIntroduction To Angular's reactive forms
Introduction To Angular's reactive formsNir Kaufman
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...Doug Jones
 
Seven Peaks Speaks - Compose Navigation
Seven Peaks Speaks - Compose NavigationSeven Peaks Speaks - Compose Navigation
Seven Peaks Speaks - Compose NavigationSeven Peaks Speaks
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Edureka!
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions WebStackAcademy
 

Tendances (20)

Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Express
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
A Brief Introduction to React.js
A Brief Introduction to React.jsA Brief Introduction to React.js
A Brief Introduction to React.js
 
jQuery
jQueryjQuery
jQuery
 
Express JS
Express JSExpress JS
Express JS
 
Angular - Chapter 5 - Directives
 Angular - Chapter 5 - Directives Angular - Chapter 5 - Directives
Angular - Chapter 5 - Directives
 
File upload using multer in node.js and express.js [2021 tutorial]
File upload using multer in node.js and express.js [2021 tutorial]File upload using multer in node.js and express.js [2021 tutorial]
File upload using multer in node.js and express.js [2021 tutorial]
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & Promises
 
Angular Directives
Angular DirectivesAngular Directives
Angular Directives
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
 
Introduction To Angular's reactive forms
Introduction To Angular's reactive formsIntroduction To Angular's reactive forms
Introduction To Angular's reactive forms
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
 
Introduction to Kotlin - Android KTX
Introduction to Kotlin - Android KTXIntroduction to Kotlin - Android KTX
Introduction to Kotlin - Android KTX
 
Seven Peaks Speaks - Compose Navigation
Seven Peaks Speaks - Compose NavigationSeven Peaks Speaks - Compose Navigation
Seven Peaks Speaks - Compose Navigation
 
Introduction to Eclipse IDE
Introduction to Eclipse IDEIntroduction to Eclipse IDE
Introduction to Eclipse IDE
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 

Similaire à Building an Android app with Jetpack Compose and Firebase

Serverless Angular, Material, Firebase and Google Cloud applications
Serverless Angular, Material, Firebase and Google Cloud applicationsServerless Angular, Material, Firebase and Google Cloud applications
Serverless Angular, Material, Firebase and Google Cloud applicationsLoiane Groner
 
Firebase on Android: The Big Picture
Firebase on Android: The Big PictureFirebase on Android: The Big Picture
Firebase on Android: The Big PictureSriyank Siddhartha
 
Lecture 11 Firebase overview
Lecture 11 Firebase overviewLecture 11 Firebase overview
Lecture 11 Firebase overviewMaksym Davydov
 
Using Java to interact with Firebase in Android
Using Java to interact with Firebase in AndroidUsing Java to interact with Firebase in Android
Using Java to interact with Firebase in AndroidMagda Miu
 
Android chat in the cloud
Android chat in the cloudAndroid chat in the cloud
Android chat in the cloudfirenze-gtug
 
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache CordovaHazem Saleh
 
TDC2016SP - Trilha Android
TDC2016SP - Trilha AndroidTDC2016SP - Trilha Android
TDC2016SP - Trilha Androidtdc-globalcode
 
Cloud Endpoints _Polymer_ Material design by Martin Görner
Cloud Endpoints_Polymer_Material design by Martin GörnerCloud Endpoints_Polymer_Material design by Martin Görner
Cloud Endpoints _Polymer_ Material design by Martin GörnerEuropean Innovation Academy
 
Comment développer une application mobile en 8 semaines - Meetup PAUG 24-01-2023
Comment développer une application mobile en 8 semaines - Meetup PAUG 24-01-2023Comment développer une application mobile en 8 semaines - Meetup PAUG 24-01-2023
Comment développer une application mobile en 8 semaines - Meetup PAUG 24-01-2023Nicolas HAAN
 
Introduction to Firebase [Google I/O Extended Bangkok 2016]
Introduction to Firebase [Google I/O Extended Bangkok 2016]Introduction to Firebase [Google I/O Extended Bangkok 2016]
Introduction to Firebase [Google I/O Extended Bangkok 2016]Sittiphol Phanvilai
 
React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsMatteo Manchi
 
Building Microservivces with Java EE 8 and Microprofile
Building Microservivces with Java EE 8 and MicroprofileBuilding Microservivces with Java EE 8 and Microprofile
Building Microservivces with Java EE 8 and MicroprofileQAware GmbH
 
Level Up Your Android Build -Droidcon Berlin 2015
Level Up Your Android Build -Droidcon Berlin 2015Level Up Your Android Build -Droidcon Berlin 2015
Level Up Your Android Build -Droidcon Berlin 2015Friedger Müffke
 
Parse cloud code
Parse cloud codeParse cloud code
Parse cloud code維佋 唐
 
Gdg dev fest hybrid apps your own mini-cordova
Gdg dev fest hybrid apps  your own mini-cordovaGdg dev fest hybrid apps  your own mini-cordova
Gdg dev fest hybrid apps your own mini-cordovaAyman Mahfouz
 
Angular 4 with firebase
Angular 4 with firebaseAngular 4 with firebase
Angular 4 with firebaseAnne Bougie
 

Similaire à Building an Android app with Jetpack Compose and Firebase (20)

Serverless Angular, Material, Firebase and Google Cloud applications
Serverless Angular, Material, Firebase and Google Cloud applicationsServerless Angular, Material, Firebase and Google Cloud applications
Serverless Angular, Material, Firebase and Google Cloud applications
 
Firebase on Android: The Big Picture
Firebase on Android: The Big PictureFirebase on Android: The Big Picture
Firebase on Android: The Big Picture
 
Apresentação firebase
Apresentação firebaseApresentação firebase
Apresentação firebase
 
Firebase overview
Firebase overviewFirebase overview
Firebase overview
 
Lecture 11 Firebase overview
Lecture 11 Firebase overviewLecture 11 Firebase overview
Lecture 11 Firebase overview
 
Using Java to interact with Firebase in Android
Using Java to interact with Firebase in AndroidUsing Java to interact with Firebase in Android
Using Java to interact with Firebase in Android
 
Android chat in the cloud
Android chat in the cloudAndroid chat in the cloud
Android chat in the cloud
 
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova
 
TDC2016SP - Trilha Android
TDC2016SP - Trilha AndroidTDC2016SP - Trilha Android
TDC2016SP - Trilha Android
 
Cloud Endpoints _Polymer_ Material design by Martin Görner
Cloud Endpoints_Polymer_Material design by Martin GörnerCloud Endpoints_Polymer_Material design by Martin Görner
Cloud Endpoints _Polymer_ Material design by Martin Görner
 
LiveOps para games usando o Firebase
LiveOps para games usando o FirebaseLiveOps para games usando o Firebase
LiveOps para games usando o Firebase
 
Comment développer une application mobile en 8 semaines - Meetup PAUG 24-01-2023
Comment développer une application mobile en 8 semaines - Meetup PAUG 24-01-2023Comment développer une application mobile en 8 semaines - Meetup PAUG 24-01-2023
Comment développer une application mobile en 8 semaines - Meetup PAUG 24-01-2023
 
Introduction to Firebase [Google I/O Extended Bangkok 2016]
Introduction to Firebase [Google I/O Extended Bangkok 2016]Introduction to Firebase [Google I/O Extended Bangkok 2016]
Introduction to Firebase [Google I/O Extended Bangkok 2016]
 
Capstone ms2
Capstone ms2Capstone ms2
Capstone ms2
 
React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applications
 
Building Microservivces with Java EE 8 and Microprofile
Building Microservivces with Java EE 8 and MicroprofileBuilding Microservivces with Java EE 8 and Microprofile
Building Microservivces with Java EE 8 and Microprofile
 
Level Up Your Android Build -Droidcon Berlin 2015
Level Up Your Android Build -Droidcon Berlin 2015Level Up Your Android Build -Droidcon Berlin 2015
Level Up Your Android Build -Droidcon Berlin 2015
 
Parse cloud code
Parse cloud codeParse cloud code
Parse cloud code
 
Gdg dev fest hybrid apps your own mini-cordova
Gdg dev fest hybrid apps  your own mini-cordovaGdg dev fest hybrid apps  your own mini-cordova
Gdg dev fest hybrid apps your own mini-cordova
 
Angular 4 with firebase
Angular 4 with firebaseAngular 4 with firebase
Angular 4 with firebase
 

Dernier

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Dernier (20)

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Building an Android app with Jetpack Compose and Firebase

  • 1. Building an Android app with Jetpack Compose and Firebase Marina Coelho Developer Relations Engineer @coelho_dev
  • 2. Firebase Authentication Firebase and Compose overview App architecture Calling async Firebase methods Firestore
  • 3. Firebase Authentication Firebase and Compose overview App architecture Calling async Firebase methods Firestore
  • 4. Drive user engagement Analytics Cloud Messaging Remote Config A/B Testing Dynamic Links In-app Messaging Improve app quality Crashlytics Performance Monitoring Test Lab App Distribution Build better apps Auth Cloud Functions Cloud Firestore Hosting Firebase ML Realtime Database Cloud Storage Extensions
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10. Jetpack Compose ● Android’s modern toolkit for building native UI ● Intuitive and requires less code than writing .xml files ● First stable version of Compose was launched in 2021
  • 11. Jetpack Compose @Composable fun Hello() { Column(modifier = Modifier.padding(16.dp)) { var name by remember { mutableStateOf(“”) } if (name.isNotEmpty()) { Text(text = "Hello, $name!") } } }
  • 12. Firebase Authentication Firebase and Compose overview App architecture Calling async Firebase methods Firestore
  • 13. Make it So ● Create and edit to-do items ● Add flags ● Add priority ● Add due date ● Mark as complete
  • 16. How it used to be private lateinit var auth: FirebaseAuth public override fun onCreate() { super.onCreate() auth = Firebase.auth } public override fun onStart() { super.onStart() val currentUser = auth.currentUser }
  • 17. How it is now class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { FirstComposableFunction() } } }
  • 18. How it is now class AccountServiceImpl() : AccountService { override fun getUser(): FirebaseUser? { return Firebase.auth.currentUser } }
  • 19. Firebase Authentication Firebase and Compose overview App architecture Calling async Firebase methods Firestore
  • 20. Synchronous and Asynchronous methods ● Synchronous ○ Returns directly to the caller ○ Blocks the caller thread ● Asynchronous ○ Processing in another thread ○ Return to caller thread once it’s completed
  • 21. How callback works fun authenticate( email: String, password: String, onResult: (Throwable?) -> Unit ) { Firebase.auth.signInWithEmailAndPassword(email,password) .addOnCompleteListener { onResult(it.exception) } }
  • 22. Firebase Authentication Firebase and Compose overview App architecture Calling async Firebase methods Firestore
  • 23. Authentication ● Knowing a user's identity allows your app to do many things ○ Securely save user data in the cloud ○ Provide the same personalized experience across all devices ● Firebase Authentication provides backend services, SDKs and UI libraries ● It supports different authentication methods ● Offers Anonymous Authentication
  • 25. Enabling it on the console
  • 26. Enabling it on the console
  • 27. Enabling it on the console
  • 28. Adding to code Add to app/build.gradle file: dependencies { implementation 'com.google.firebase:firebase-auth-ktx' } Sync Android project with Gradle files again
  • 29. Providing the ViewModel @HiltViewModel class LoginViewModel @Inject constructor() : ViewModel() { var uiState = mutableStateOf(LoginUiState()) private set }
  • 30. The Screen @Composable fun LoginScreen( [...], viewModel: LoginViewModel = hiltViewModel() ) { val uiState by viewModel.uiState }
  • 31. The UI State data class LoginUiState( val email: String = "", val password: String = "" )
  • 32. The Screen OutlinedTextField( singleLine = true, modifier = Modifier.fillMaxWidth(), value = uiState.email, onValueChange = { viewModel.onEmailChange(it) }, placeholder = { Text(stringResource(R.String.email)) }, )
  • 33. The Screen Button( onClick = { viewModel.onSignInClick() }, Modifier = Modifier.fillMaxWidth() ) { Text(text = stringResource(R.String.sign_in)) }
  • 34. The ViewModel fun onSignInClick() { viewModelScope.launch(exceptionHandler) { accountService.authenticate(email, password) { error -> if (error == null) { linkWithEmail() } else onError(error) } } }
  • 35. Firebase Authentication Firebase and Compose overview App architecture Calling async Firebase methods Firestore
  • 36. Cloud Firestore ● NoSQL document database in the Cloud ● Data is stored into structures called documents ● Retrieve individual or list of documents ● Listen to changes across client apps ● Offers offline support
  • 37. What a document looks like in Make it So
  • 38. Mapping data data class Task( val id: String = “”, val title: String = "", val priority: String = "", val dueDate: String = "", val dueTime: String = "", val description: String = "", val url: String = "", val flag: Boolean = false, val completed: Boolean = false, val userId: String = "" ) val task = result.toObject<Task>()
  • 39. Enabling it on the console
  • 40. Adding to code Add to app/build.gradle file: dependencies { implementation 'com.google.firebase:firebase-firestore-ktx' } Sync Android project with Gradle files again
  • 41. The service val query = Firebase.firestore .collection(TASK_COLLECTION) .whereEqualTo(USER_ID, userId) query.addSnapshotListener { value, _ -> value?.documentChanges?.forEach { val wasDocumentDeleted = it.type == REMOVED onDocumentEvent( wasDocumentDeleted, it.document.toObject<Task>() ) } }
  • 42. The ViewModel private fun onDocumentEvent(wasDocumentDeleted: Boolean, task: Task) { if (wasDocumentDeleted) tasks.remove(task) else updateTaskInList(task) } private fun updateTaskInList(task: Task) { val index = tasks.indexOfFirst { it.id == task.id } if (index < 0) tasks.add(task) else tasks[index] = task } var tasks = mutableStateListOf<Task>() private set
  • 43. The Screen val tasks = viewModel.tasks LazyColumn { items(tasks, key = { it.id }) { taskItem -> TaskItem( task = taskItem, onCheckChange = { viewModel.onTaskCheckChange(taskItem) }, onActionClick = { action -> viewModel.onTaskActionClick(openScreen, taskItem, action) } ) } }
  • 44. There's a lot more in Firestore! fun addListener( userId: String, onDocumentEvent: (Boolean, Task) -> Unit, onError: (Throwable) -> Unit ) fun removeListener() fun getTask(taskId: String, onError: (Throwable) -> Unit, onSuccess: (Task) -> Unit) fun saveTask(task: Task, onResult: (Throwable?) -> Unit) fun deleteTask(taskId: String, onResult: (Throwable?) -> Unit) fun deleteAllForUser(userId: String, onResult: (Throwable?) -> Unit)
  • 45. Firebase Authentication Firebase and Compose overview App architecture Calling async Firebase methods Firestore
  • 46. Make it So Series Github @coelho_dev Blog