Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

View nanlabsweb's full-sized avatar

nanlabsweb

View GitHub Profile
import { ageSelector, regionSelector, isEligibleSelector} from './CoolModuleSelectors.js';
(...)
const mapStateToProps = state => ({
age: ageSelector(state),
region: regionSelector(state),
isEligible: isEligibleSelector(state),
});
(...)
import { createSelector } from 'reselect';
const birthDateSelector = state => state.user.birthdate;
const countrySelector = state => state.user.location.country;
export const ageSelector = createSelector(
birthDateSelector,
dateString => moment().year() - moment(dateString).year(),
);
const mapStateToProps = state => ({
birthDate: state.user.birthdate,
country: state.user.location.country,
});
@nanlabsweb
nanlabsweb / suspendCoroutine.kt
Created April 5, 2018 16:20
Managing exceptions inside a coroutine.
suspend fun <T> Task<T>.await(): T = suspendCoroutine { continuation ->
addOnCompleteListener { task ->
when {
(task.result as QuerySnapshot).metadata.isFromCache ->
continuation.resumeWithException(Exception("without internet"))
task.isSuccessful -> continuation.resume(task.result)
else -> continuation.resumeWithException(task.exception!!)
}
}
}
@nanlabsweb
nanlabsweb / getAllPetsWithCoroutines.kt
Created April 5, 2018 16:18
Get data from firestore with Coroutines.
suspend fun getAllPets(): List<Pet> {
val result = firestoreDataBase.collection("pets").get().await()
return setPetsFromSnapshotIntoMutableList(result)
}
@nanlabsweb
nanlabsweb / getAllPets.kt
Created April 5, 2018 16:17
Get data from firestore.
fun getAllPets(): LiveData<List<Pet>> {
var pets: MutableLiveData<List<Pet>> = MutableLiveData()
firestoreDataBase.collection("pets").get().addOnSuccessListener {
pets.value = setPetsFromSnapshotIntoMutableList(it)
}
return pets
}
@nanlabsweb
nanlabsweb / SyncRepoWithCoroutines.kt
Created April 5, 2018 16:16
Sync repository with coroutines.
suspend fun syncPets() {
val pets = firestoreWrapper.getAllPets()
appDataBase.petDao().deleteAllPets()
pets.forEach {
appDataBase.petDao().insert(it)
}
}
@nanlabsweb
nanlabsweb / SyncRepoWithoutCoroutines.kt
Created April 5, 2018 16:14
Sync Repository without coroutines.
fun syncPets(): LiveData<List<Pet>> {
liveDataMerger.addSource(firestoreWrapper.getAllPets()) {
value -> liveDataMerger.value = value
appDataBase.petDao().deleteAllPets()
value?.forEach {
appDataBase.petDao().insert(it)
}
}
return liveDataMerger
}
@nanlabsweb
nanlabsweb / syncPetsFn.kt
Created April 5, 2018 16:13
Sync pets with exception handling.
suspend fun syncPets(): String {
var message = "Congratulations!!"
try {
async { repository.syncPets() }.await()
} catch (e: Exception) {
message = e.message!!
}
return message
}
@nanlabsweb
nanlabsweb / syncPetsCoroutines.kt
Created April 5, 2018 16:11
Sync Pets with coroutines
suspend fun syncPets() = repository.syncPets()