1
votes

Is there any operator in RxJava2 which can apply a transformation from Flowable to Single or Maybe? I mean Flowable.compose() operator applies a Transformer to a Flowable and returns another Flowable. But I need to apply a transformer which converts a Flowable into a Single or Mabye and which can further be reused multiple times in my application without "breaking the chain".

Example (in Kotlin):

fun processFirstEven(f: Flowable<Int>): Maybe<Int> {
    return f.filter { i -> i % 2 == 0 }.take(1).singleElement().map { s -> s * 12 }
}

val f: Maybe<Int> = Flowable
        .fromArray(1, 3, 5, 6, 7, 8, 9)
        .compose(::processFirstEven) // Does not compile
1
To transform between the base types, use to or as instead of compose. - akarnokd
Thank you @akarnokd This looks like what I am looking for. Would you please post this comment as an answer, so I could mark it as accepted? - Uniqus
I can't. SO will flag it as trivial/link only and delete it. - akarnokd

1 Answers

1
votes

I don't think there is a way to do this kind of complex transformation in a single line. It looks this is already quite simple for me:

fun takeFirstEven(f: Flowable<Int>): Flowable<Int> {
    return f.filter { i -> i % 2 == 0 }.take(1)
}

val f: Maybe<Int> = Flowable
    .fromArray(1, 3, 5, 6, 7, 8, 9)
    .compose(::takeFirstEven)
    .singleElement()

The good news is that if your goals is just the reusablility, you can use Kotlin's function extension feature to do exactly that.

Put this code somewhere your code can access:

fun <T> Flowable<T>.toMaybe(filter: (T) -> Boolean): Maybe<T> {
    return this.filter(filter).take(1).singleElement()
}

Then you can simply use toMaybe anywhere with any filter you would like.

fun evenFilter(i: Int) = (i % 2) == 0

val f: Maybe<Int> = Flowable
    .fromArray(1, 3, 5, 6, 7, 8, 9)
    .toMaybe(::evenFilter)