SlideShare uma empresa Scribd logo
1 de 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!

Mais conteúdo relacionado

Mais procurados

Kubernetes Scheduler deep dive
Kubernetes Scheduler deep diveKubernetes Scheduler deep dive
Kubernetes Scheduler deep diveDONGJIN KIM
 
Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Knoldus Inc.
 
Managing Terraform Module Versioning and Dependencies
Managing Terraform Module Versioning and Dependencies Managing Terraform Module Versioning and Dependencies
Managing Terraform Module Versioning and Dependencies Nebulaworks
 
Towards Functional Programming through Hexagonal Architecture
Towards Functional Programming through Hexagonal ArchitectureTowards Functional Programming through Hexagonal Architecture
Towards Functional Programming through Hexagonal ArchitectureCodelyTV
 
Veracode Automation CLI (using Jenkins for SDL integration)
Veracode Automation CLI (using Jenkins for SDL integration)Veracode Automation CLI (using Jenkins for SDL integration)
Veracode Automation CLI (using Jenkins for SDL integration)Dinis Cruz
 
SwiftUI와 TCA로 GitHub Search앱 만들기
SwiftUI와 TCA로 GitHub Search앱 만들기SwiftUI와 TCA로 GitHub Search앱 만들기
SwiftUI와 TCA로 GitHub Search앱 만들기규영 허
 
Jetpack Compose a nova forma de implementar UI no Android
Jetpack Compose a nova forma de implementar UI no AndroidJetpack Compose a nova forma de implementar UI no Android
Jetpack Compose a nova forma de implementar UI no AndroidNelson Glauber Leal
 
SOAP To REST API Proxy
SOAP To REST API ProxySOAP To REST API Proxy
SOAP To REST API ProxyVince Soliza
 
Hyperledger Fabric practice (v2.0)
Hyperledger Fabric practice (v2.0) Hyperledger Fabric practice (v2.0)
Hyperledger Fabric practice (v2.0) wonyong hwang
 
[2018] MyBatis에서 JPA로
[2018] MyBatis에서 JPA로[2018] MyBatis에서 JPA로
[2018] MyBatis에서 JPA로NHN FORWARD
 
webpack 101 slides
webpack 101 slideswebpack 101 slides
webpack 101 slidesmattysmith
 
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!Ryosuke Uchitate
 

Mais procurados (20)

Kubernetes Scheduler deep dive
Kubernetes Scheduler deep diveKubernetes Scheduler deep dive
Kubernetes Scheduler deep dive
 
Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2
 
Managing Terraform Module Versioning and Dependencies
Managing Terraform Module Versioning and Dependencies Managing Terraform Module Versioning and Dependencies
Managing Terraform Module Versioning and Dependencies
 
Scala cheatsheet
Scala cheatsheetScala cheatsheet
Scala cheatsheet
 
Towards Functional Programming through Hexagonal Architecture
Towards Functional Programming through Hexagonal ArchitectureTowards Functional Programming through Hexagonal Architecture
Towards Functional Programming through Hexagonal Architecture
 
Veracode Automation CLI (using Jenkins for SDL integration)
Veracode Automation CLI (using Jenkins for SDL integration)Veracode Automation CLI (using Jenkins for SDL integration)
Veracode Automation CLI (using Jenkins for SDL integration)
 
SwiftUI와 TCA로 GitHub Search앱 만들기
SwiftUI와 TCA로 GitHub Search앱 만들기SwiftUI와 TCA로 GitHub Search앱 만들기
SwiftUI와 TCA로 GitHub Search앱 만들기
 
Jetpack Compose a nova forma de implementar UI no Android
Jetpack Compose a nova forma de implementar UI no AndroidJetpack Compose a nova forma de implementar UI no Android
Jetpack Compose a nova forma de implementar UI no Android
 
Angular Directives
Angular DirectivesAngular Directives
Angular Directives
 
SOAP To REST API Proxy
SOAP To REST API ProxySOAP To REST API Proxy
SOAP To REST API Proxy
 
CRI, OCI, and CRI-O
CRI, OCI, and CRI-OCRI, OCI, and CRI-O
CRI, OCI, and CRI-O
 
Hibernate
HibernateHibernate
Hibernate
 
Hyperledger Fabric practice (v2.0)
Hyperledger Fabric practice (v2.0) Hyperledger Fabric practice (v2.0)
Hyperledger Fabric practice (v2.0)
 
Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
 
Entity Framework
Entity FrameworkEntity Framework
Entity Framework
 
JSX
JSXJSX
JSX
 
[2018] MyBatis에서 JPA로
[2018] MyBatis에서 JPA로[2018] MyBatis에서 JPA로
[2018] MyBatis에서 JPA로
 
Ngrx
NgrxNgrx
Ngrx
 
webpack 101 slides
webpack 101 slideswebpack 101 slides
webpack 101 slides
 
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
 

Semelhante a Build Android Apps 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
 

Semelhante a Build Android Apps 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
 

Último

What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 

Último (20)

What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 

Build Android Apps 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