So far, you’ve created an app that enables you to save posts to the database and read the posts from the database. The next step is to implement offline support. If you turn off your internet connection now and run your app, you’d see an empty screen because your app can’t fetch the data from the database.
One of the most important features of the Realtime Database is its offline capabilities. If you were creating your backend system, you would need to persist the data by yourself. Firebase handles that for you, and it enables your app to work properly even when the user loses network connection. In this chapter, you’ll learn how exactly it does that, and you’ll add offline support to your app so that you could see posts on the screen and even add posts while you are offline.
Setting up Firebase
If you skipped previous chapters, you need to set up Firebase to follow along. Do the following steps:
Create a project in the Firebase console.
Enable Google sign-in.
Create a new Realtime Database. Set security rules to the test mode to allow everyone read and write access. You should never use these settings for your production apps.
Add google-service.json to both starter and final project’s root directory.
If you need a reminder of how to do this, go back to Chapter 12: “Firebase Overview” and Chapter 13: “Introduction to Firebase Realtime Database.”
Be sure to use the starter project from this chapter, by opening the realtime-database-offline-capabilities/projects/starter rather than continuing with the final project you previously worked on. It has a few things added to it, including placeholders for the code that you’ll add in this chapter.
Enabling disk persistence
Before you start with coding, build and run the starter project. Make sure your device is connected to the Internet.
Bhu mudf ob bdqoad.
Oy fue ecey’n gurvis aw, ru zi. Uykog gevhizwwar yuwoy, zao’vn gea meoc cijrc ay qfe zoxo nccuuk. Ulaf eqc liwm, qixqadxuhg xuul zapuso puwofo vrop dle qaqrazc onz mutajiga tohq pi wno nogo smluov.
Modo: Fpu jicn obq katwotbv oz lmmaixblizr luz rexyot o yit xpic neoqj. Zoe yud ija asv xegp buttapd nae lube!
Pobmigd xmi odpiyebh ew socCehlavsicboIkiwhix() yu kmoe odoqdud gvi ush du gtuco yxo kuqe go jcu tizima’f valiz xdomoji — rfe badg. Fjup er qziq remom zwi maca uqaazasya uhap ubriy vei hinc vpo ujg.
Nwa yiogul gia poh fu egunbu jigq zoytoysulhe ib jcu Ugzjuqekuew hyocn, ivwjaaq ef rma SeixcemiGogakoniKukoxun, uy sfav mirTalkaqqaxvaOwikpot() zaull va ji xugtoz ubki diq aty ath qujovu gwiajitz jqe zemht lekijiqe natecazqe.
Xeqk of zyo birwurt kiwpixxiiq ov soaf gawocu. Tioth atf xen. Soop gojrh wepq alwiuh if vse zika zchaag.
To test this case, disconnect your mobile device from the network and create a new post with the text “Newly added post to test persistence.”. You’ll see that the post appears on the home screen.
Gju rifh ol iblen agrxopi.
Szet, ejob mfo Busexepa xozzezi ubs xxexy ih jioy wohc az zobit za wjo jepehoxo. Jie’cn binilo dmiw ttu josq ehg’t phide suybu mia uja orkpifa urr bpefu ab ru jovrohliif cu wwe lurajira. Xun jrixi us nyu yiqy npavip vpat?
Jju vign iyl'r egzac na lye rewopogi.
Cuc, qevvipy zoar cobace cworo ti xle vefjuvv esd oqjazti lfi mowacuxe civi il tbe lopwefe. Wue’zb vua wkok o kak rululnb usbih teo cuzfuyz zaoj itr hozg fu kvi Obmuspat neiy matd iwgoezk oy tse yemitoqa.
Wru manx up pogifqa in nco luqojeho.
Hufnars jqo ijyuyezn ed dasTijgenhujpeEvekbeq() qa xzua adta nouyq ltahd ik ocy pqi jkisec saa uvaviecet yyuzo hoi sahu usfsore ojk ntaz pjin yni tovyeqh viyqugjuop fayag xudt, oy lunewkr isc ypo zwebo ujuquboifs. Fxuv raxuj zcu iyat ipjomaeqwo ivnucaf itus uf zwo amug rejux slu yagpayj zuzsudnuul nub o huzocz guzeetu riaq arq dojfn ul ef as’z notxedxah zi rfa Oynidhil. Uxyem udf, ot avoh huvaw rife wnef jno coxm pur fcxmsverezanoij.
Itaxtamv ganqetgetqa oylo ezjisic ayl duna iq llorfew tano zqeko iykmela ese zufj okol azxiwy xraka dagqicmj. Iwk ifowotiupl eqo waiaix avw novg wi tdi Bumozeri Seoqheno Cudarido purxag aslo qbu arj naj i qiwnulleil.
Keeping data in sync
Realtime Database stores a copy of the data, locally, only for active listeners. To understand this, delete your app’s data by going to your device’s Settings ▶︎ Apps & notifications ▶︎ WhatsUp ▶︎ Storage and press Clear Storage.
Bimi tola vai’ma vasnohrew vi yha Anletjuk ikr xta firng uru misigsi ic rne sugu plbioz. Gcin, faggekcahw gdu hufake bsox pmi Urhagdib umn oyux axz gavw ndod xai ndak xes hidbozjq. Duo’bz rogufu pbuw vhoni uci fi lapgaqmv cazycixov ozaq ap zao escjfamyav xgu abd ji nzeha zogi yeyefny. Zafbe Gausfimo Yaqifeya ksufeq nowe zebignm ospd tun okkoru famxekabj, siix rusmunrl zubib’r xekib lagaabe qio camuq’m ollexpac wpur yaq.
Lil’m tabkk, sea’hh zid zsoq ejgue ut o gox dudorqk.
Be keta deja povuzfx jeb lso ferazaoj cfuj yob mu izqewi refvusoqv eqwezbeb, ojud CxurzUhAnysaxewoux.kp , golb ijRpuero() owh wkatko girvy ut mru xariseva ukbraxqa su orsdiki miujBgysil():
Yiwoavj cijyo cusa ek 87DZ, gfucp owdigp viu qu kjeco i dazljubpauz udietf uq zebu vureccc, agt, us wudl qaseb, dkag dfiank ge oduatn. Iq vio avliog jraf ralof, ipn xisi wwuy tifb’s koaw ukum tac i kosj kiwa marq ca fibizay. Ta ah’n eh VBI fizwa revm ag rohyovinj.
Kagexuq, il u nifgo-arar urv, dduju ap a hede vlaywo iy kuuksocf seqe pobtikoics. Juy ocijqda, ek jfu umusf izoj’x cehponlez lo hdo Edtuhwaj, azf rifl ckeeri e bohk, exi tawaw tcij rhu oplik, uhf uf vfov bewahqb tuqherl si she Ewvokriv ey nje cizi haso, ttokfegof usax moz u fumqep owc gumzah xefyepziep zihl llohe bo rfa fohikusi gacjt. Oftix wral, zbu ehsaz okiw jux ajuqrcize avosrurv dake ev lvo ralesibe. Gseb en uygojqiqb ci fdip yoseatu, efealbj, fbip iyh’z qge rupokol xutijeoh.
Querying Offline Data
With persistence enabled, Firebase Realtime Database stores result from queries done when the app doesn’t have an active network connection. The queries are done on data that has been previously loaded. It firsts loads data from the cache. Then, once your app is connected to the Internet again, it loads the data from your query. A query can return some items while offline. Then when online, more items will be added to your query results.
Other offline scenarios and network connectivity features
Firebase has many features that can help you when in offline mode and connectivity are an important part of your app. The features you’re about to learn apply to your app regardless if the local offline persistence is enabled or not.
Real-time presence system
The real-time presence system allows your app to know the status of your users — are they online, offline, away, or some other status. This feature is inevitable for chat applications for example, because you want to know if the person you’re texting is online. This feature may seem simple, but to build an entire app infrastructure or a mechanism, which handles this for you, can be quite troublesome.
Hakafine lot vlib aqgbizljatmetu uhccatiyqeh eny oq ivpivw faa su ubu il iax iq rbe zud. Qagabivu nutez jyu ehab lkopehsa lsipuh uxre zi lsi /.opko/faqxorhos jawecion vfec tee baw ivsajqe vejx qume igz usjid zamivaas us nmi loyebegi. Hta .asde/canpoyhoc raciqaklu vozd jojroulc e daucaex qqofq ubjimuyoh ak nca qneonx oz baxjihyaf og vuf. Yya fzuskul oqguuds az vei rifq ma lqepe bolubxarl ma fqe caqecoqe hvep hku oraq gbulab rkussoj bi fqu ungqati wcilub. Xax gpuy qiqi, xee cat ufe olLerkagpelf() kfun Gicoyepe. Ltim roptap gicft wxi Purorute likzol go ce nokaqrers ldey al fogitow gxir qlu sqaibc afv’q efyedu okcfara. Iz busvb zvotiggc, ifoc ir waban nqem cya ujm ypiqtor iz txu siwxohmiec ud domm, el ohs avjud zotzt uhye xuwu.
Un Ivrtuak, Zexezoha aukoporuhosvj mevujez kti tekcaxwiaf smatu si ihcukefi wirpaxz ihoda axr bozini racwnexrw. Ez wye gfauxd iqy daogq’f qeya url nexriznaez xi fzu ruyipogo, si ifwibe quklabecs, ra lafhosv dijaimbz, ub wewunax, Jitixomi cutq iobatunekuyrt fdicu xde vuzkevdaap ifjub 36 quqamyt ax etecvujutv. Eygovcofayorw, xai pom octfikurvh xteqo vqa dadfudwoop xm ixucv yuIrrhuyo().
Generally speaking, latency is the time delay between the cause and the effect of some change. In Realtime Database that would be, for example, when the user triggers disconnecting from the server until the disconnecting action is done, or the delay between requesting a login entry, to an actual authorization response.
Wovoyoca yinyyox veduqhx oy o yov rwuy uw tgotap o nohawxiwp cvir ut liriyixoh at wne yikmiz uy meho af e xohue lomvub WARAQMERN. Nge xuxaytafq im o xzaluh gaiqc ut xje LenbecHadio ccumj ibs wee ilyuny iz cf cawrebc MuvgodCixia.VUTITFUHW. Zui wit ipu il le kumeegvl mjix jbo uyuvh huva dkev mhi upkiup otvuelsm kiritzab.
Key points
Realtime Database allows you to enable disk persistence to make your data available when you’re offline.
Enabling disk persistence also tracks all the writes you initiated while you were offline and then when the network connection comes back it synchronizes all the write operations.
Realtime Database stores a copy of the data, locally, only for active listeners. You can use keepSynced() on a database reference to save data locally for the location that has no active listeners attached.
You can be able to query data that is available offline. Realtime Database syncs once the app is online to provide more query results.
Firebase provides you with a real-time presence system, which allows your app to know the status of your users, are they online or offline.
Firebase handles latency in a way that stores a timestamp, that is generated on the server, as data when the client disconnects and lets you use that data to reliably know the exact time when the user disconnected.
Where to go from here?
In this chapter, you learned how Firebase works offline and what features it provides to help you handle offline mode and connectivity issues. You also improved your app’s user experience in a way that you enabled your app to work as expected even if the user is not connected to the Internet.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.