Skip to content

Instantly share code, notes, and snippets.

View gastsail's full-sized avatar
🎯
Focusing

Gastón Saillén gastsail

🎯
Focusing
View GitHub Profile
private val cartHashMap = MutableLiveData<HashMap<String,Cart>>()
private var sharedHashMap = HashMap<String,Cart>()
fun setProductSelectedHashMap(productId:String,productSelected:Cart){
sharedHashMap[productId] = productSelected
cartHashMap.value = sharedHashMap
}
fun removeSelectedProduct(productId:String){
sharedHashMap.remove(productId)
//1 .- We use callbackFlow , this is like channelFlow and will propagate our data to our viewmodel
override suspend fun getVersionCodeRepo(): Flow<Resource<Int>> = callbackFlow {
// 2.- We create a reference to our data inside Firestore
val eventDocument = FirebaseFirestore
.getInstance()
.collection("params")
.document("app")
// 3.- We generate a subscription that is going to let us listen for changes with
class MainViewModel(repo:Repo):ViewModel() {
val fetchVersionCode = liveData(Dispatchers.IO) {
emit(Resource.Loading())
try{
repo.getVersionCode().collect {
emit(it)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
observeData()
}
private fun observeData(){
viewModel.fetchVersionCode.observe(this, Observer { result ->
when(result){
val postListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
// Get Post object and use the values to update the UI
val post = dataSnapshot.getValue(Post::class.java)
// ...
}
override fun onCancelled(databaseError: DatabaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException())
private val viewModel by lazy { ViewModelProviders.of(this, EventsVMFactory(EventsImpl(EventsRepoImpl()))).get(EventsViewModel::class.java) }
...
override fun onCreate() {
viewModel.fetchEventList.observe(this, Observer {
when(it){
is Resource.Loading -> {
// Before try catch in viewmodel we can use emit(Resource.Loading()) to tell the view we started fetching results and this will be triggered
}
class EventsVMFactory(private val useCase: IEvents):ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return modelClass.getConstructor(IEvents::class.java).newInstance(useCase)
}
}
class EventsViewModel(private val useCase: IEvent):ViewModel() {
val fetchEventList = liveData(Dispatchers.IO){
try {
val eventList = useCase.getEvents()
emit(eventList)
}catch (e:Exception){
Crashlytics.logException(e.cause)
emit(Resource.Failure(e.cause!!))
class EventsRepoImpl : IEventsRepo {
override suspend fun getEventsDB(): Resource<MutableList<Event>> {
val eventList = mutableListOf<Event>()
val resultList = FirebaseFirestore.getInstance()
.collection("events")
.get().await()
for (document in resultList) {
val photoUrl = document.getString("photoUrl")
interface IEventsRepo {
suspend fun getEventsDB(): Resource<MutableList<Event>>
}