I'm trying to achieve the following in a Rx comman...
# rx
s
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?
g
The way I split streams is with a
flatMap
.
And to aggregate you could
reduce
.
🙏 1
c
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
Single.just(listOfLocations)
    .flattenAsObservable { it }
    .flatMapSingle { locationToObject(it) }
    .toList()
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
s
Indeed still relevant, I'll look into this comment over the weekend. Thanks @CamiloVega