Hi, I have a `fun getResources(): Single<Resour...
# rx
m
Hi, I have a
fun 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:
Copy code
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?
e
You could do something like
Copy code
getResources()
    .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.
Copy code
inline fun <T> Single<T>.forEachCompletable(block: (T) -> Completable) = flatMap { /* like in the previous snippet */ }
So you could do
Copy code
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.
m
Thank you! Your right with this code I can handle this scenario but, as you said, I’d prefer if it could be concurrent... I think that a more general question would be “How do I manage ‘fire and forget’ flows with observables”? Maybe observables it’s not the best way to do this because I don’t want to observe anything about that?
e
If it's an Android situation, I would probably add a method to the Application class, something like
fun 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.
If it's not Android, then I'm sure there must be something you can use to fire off these requests that lives/can live for the whole lifecycle of the application.
m
it’s a server app, maybe I can launch a coroutine in this case, thanks for the help!