Link designer Kotlin with generics

I have this code in (Rx) Java:

Observable.fromArray(1, 2, 3)
    .flatMap(this::intToBooleanObservable, Pair::new)
    .....

I expect the corresponding Kotlin code to look like this:

Observable.fromArray(1, 2, 3)
    .flatMap(::intToBooleanObservable, ::Pair)
    .....

However, the compiler cannot deduce the general type of the pair, so the best I can do right now is:

.flatMap(::intToBooleanObservable, { a, b -> a to b })

This is not as concise as we would like.

Is there a way to achieve this without declaring variables aand b?

+6
source share
1 answer

The same problems are here. A few other workarounds (in the order I used them), you might like one of them.

1) Writing your own operator:

fun <T, U> Single<T>.flatMapPair(func: (T) -> Single<U>) : Single<Pair<T, U>> {
    return this.flatMap { t -> func.invoke(t).map { u -> t to u } }
}

2) Observable ( intToBooleanObservable), ( , Success and Failure). :

 when(it) {
   is Success -> ...
   is Failure -> ...
}

3) intToBooleanObservable 2 ( ). /, . , , :

fun <T> Observable<T>.filterSingle(predicate: (T) -> Single<Boolean>, rejectionFunction: (T) -> Unit): Observable<T> = ... //filter with the given predicate, and call rejectionFunction if item doesn't pass

4) . , / ? . , Aither + RxJava; mapRight, flatMapRight dropLeft. dropLeft - filterSingle.

inline fun <L, R> Observable<Either<L, R>>.dropLeft(crossinline sideEffect: (L) -> Unit): Observable<R> = this.lift { downObserver ->
    object: Observer<Either<L, R>> {
        override fun onError(throwable: Throwable?) = downObserver.onError(throwable)

        override fun onSubscribe(disposable: Disposable?) = downObserver.onSubscribe(disposable)

        override fun onComplete() = downObserver.onComplete()

        override fun onNext(either: Either<L, R>) = when (either) {
            is Right -> downObserver.onNext(either.value)
            is Left -> sideEffect(either.value)
        }
    }
}

, .

+1

All Articles