Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle a Boolean Value in Firebase Realtime Database

I am accessing my firebase database from my android app. I need to implement like functionality like facebook. So when the user presses like button, if the post is already liked it gets unliked and vice versa. For that purpose, I am first checking if the liked boolean field is true in the firebase and if it is, then update it to false and vice versa. My current approach includes reading the liked field and then writing it (doing 2 DB Calls).

Is there any native solution provided by Firebase for this?

Toggling a boolean value in Firebase Database

like image 484
shikhar bansal Avatar asked Oct 18 '22 18:10

shikhar bansal


1 Answers

This way is a bit nasty and not very good actually, but it work and fastest way (I think).

Instead of boolean, make your parameter integer. Every time the like button clicked, add +1 value into it, and whenever you read that data, you just need to confirm if it's odd or even. Odd is for like, even for not like, or vice versa.

like image 181
koceeng Avatar answered Oct 28 '22 15:10

koceeng