Matias Reparaz
08/20/2021, 5:47 PMfun getResources(): Single<Resources>
and with that I need to do 2 things, 1️⃣ a flatMap with another call fun doSomething(r: Resources): Single<OtherThing>
and 2️⃣ send a metric if some condition occurs fun sendMetric(r: Resources): Completable
.
I’m looking for something better than this:
getResources()
.doOnSuccess {
if (someCondition(it)) sendMetric(it).subscribe()
}.flatMap { doSomething(it) }
Note that if sendMetrics
fails it’s not critical and I don’t want to interrupt the doSomething
flow. Is there a more elegant way to do this?Edgars
08/20/2021, 8:26 PMgetResources()
.flatMap { resources ->
if (someCondition(resources) {
sendMetric(resources)
.onErrorComplete()
.andThen(doSomething(it))
} else {
doSomething(it)
}
}
I usually create an extension function for things like that, eg.
inline fun <T> Single<T>.forEachCompletable(block: (T) -> Completable) = flatMap { /* like in the previous snippet */ }
So you could do
getResources()
.forEachCompletable { if (someCondition(it)) sendMetric(it) else Completable.complete() }
.flatMap { doSomething(it) }
I don't suppose that looks very elegant, but if you abstract it behind a reusable function, it's alright. 🙂
This won't help if you need sendMetric
to happen in parallel with doSomething
, though.Matias Reparaz
08/23/2021, 12:45 PMEdgars
08/23/2021, 1:09 PMfun fireAndForget(observable: Observable<*>)
, and subscribe there. Don't really have to worry about memory leaks or anything, it's not an Activity. Of course, generally, I'd prefer to have, say, an Analytics
class that is a singleton, to which you can feed metrics and it will send them, to load off that responsibility from whatever class is doing it.Edgars
08/23/2021, 1:10 PMMatias Reparaz
08/23/2021, 1:13 PM