# rx

Sami Eljabali

12/02/2020, 4:53 AM
I'm trying to achieve the following in a Rx command: 1) Get all locations & their cached temperatures from db. 2) For every missing cached temp, fetch temp from api. 3) Aggregate temps & return. I did #1, leaving me with a mixed bag of areas with cached temperatures and areas needing api fetches. • How do I split this stream into 2? • How do I then aggregate the results into 1 list after the stream needing api fetches is done?

Guillermo Alcantara

12/02/2020, 5:16 AM
The way I split streams is with a
And to aggregate you could
🙏 1


12/16/2020, 11:28 PM
dont know if this is still relevant, and dont know the exact commands of the top of my head, but assuming you have a list of locations you can
Copy code
//your list of location strings
val listOfLocations = emptyList<String>()
//your cache object that contains the location and the temperature 
var location = Location("")

//this would be a method that talks to the db, you pass in a string and returns a maybe, if the location is there, it returns it
fun getLocationForString(it: String) = Maybe.just(location)

//This is your api call to get the location and temperature (do what ever aggregations needs to be done for location + temp)
fun getLocationFromApi(it: String) = Single.just(location)

//This is a method on your Data repository, it looks up the object on cache, if its empty, it fetches it from api
fun locationToObject(it: String): Single<Location> = getLocationForString(it)
    .switchIfEmpty (getLocationFromApi(it))

//This is the method that takes the list of your locations, and creates a single, then flattens it a creates an observable for every item, then a flatmap single to get the location object (from cache and if empty from api) and then .toList makes the subscription wait until all of the emissions from the original list have gone through all the mapping and emits  a list of all the Locations
    .flattenAsObservable { it }
    .flatMapSingle { locationToObject(it) }
I know its not extremely clear, and the Maybe and Single.just is to ilustrate but should be replaced with whatever logic you have to retrieve your locations from db or api

Sami Eljabali

12/16/2020, 11:31 PM
Indeed still relevant, I'll look into this comment over the weekend. Thanks @CamiloVega