AndroidPub
Published in

AndroidPub

Firebase, Redux, Observables.

Interactive marble diagram from http://rxmarbles.com

What could possibly be the benefit of adding this entire library and adding the extra cognitive load to do something I can already do with modern JavaScript? — Me, evaluating Observables

I usually use React when I write Single Page Apps, and add Redux when I need some sane state management. This works well when you have simple functions that make backend calls and update state when the result is received, however firebase uses WebSockets to give you realtime updates as your data changes. In order to use this functionality, you need to essentially subscribe to all the changes to data and update your state accordingly.

  • the ability to cancel incomplete http requests (to avoid computations that happen when invalid requests complete, e.g. that evil “setState on unmounted component” error)
  • the ability to unsubscribe from events when components are unmounted
  • automatic cleanup of resources with `Observable.using`
  • the ability to use other observables to subscribe to related events e.g. subscribing to profile events for the currently logged in user
const dbRef = path => firebase.database().ref(path);
const observeOn = event => obj => Observable.fromEvent(obj, event);
const setRef = data => ref => ref.set(data);
const getVal = snapshot => snapshot.val();
/**
* Emits a `user` object when a user signs in
* Emits null when a user signs out
*/
export const authChanged = Observable.using(firebase.auth, auth =>
Observable.create(observer =>
auth.onAuthStateChanged(user => observer.next(user)));
export const profileRefSource = authChanged
.filter(Boolean) // ignore logged out users
.pluck('uid')
.map(concat('users/'))
.map(dbRef);
export function getProfile() {
return profileRefSource
.flatMap(observeOn('value'))
.map(getVal);
}
// bonus function for updating the user's profile using the same observable
export function updateProfile(profile) {
return profileRefSource
.map(setRef(profile));
}

--

--

The (retired) Pub(lication) for Android & Tech, focused on Development

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alpha Shuro

Most of my life is spent on practical philosophy, coding, gaming, and living.