s-hunter
s-hunter

Reputation: 25816

How can I convert this rxjava/rxkotlin flatMap into lambda expression?

    Observable.just(1)
            .flatMap(object : Function<Int, Observable<Int>> {
                override fun apply(integer: Int): Observable<Int> {
                    return Observable.just(integer * 10)
                }
            })
            .flatMap(object : Function<Int, Observable<Int>> {
                override fun apply(integer: Int): Observable<Int> {
                    return Observable.just(integer * 20)
                }
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<Int> {
                override fun onComplete() {
                }

                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: Int) {
                    Log.d("result", "" + t)
                }

                override fun onError(e: Throwable) {
                    e.printStackTrace()
                }
            })

Upvotes: 6

Views: 6088

Answers (2)

Antek
Antek

Reputation: 739

actually, return@flatMap is not needed, so below works as well. Also, if you don't need all methods for a subscriber actually implemented, there's an overload with just onNext and onError. IDE's hints are of great help in here - when typing in a method, press Ctrl+P and it will show you available overloads. The keyboard shortcut is essentially "show me arguments".

    Observable.just(1)
        .flatMap { Observable.just(it * 10) }
        .flatMap { Observable.just(it * 20) }
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
                { Log.d("result", "" + it) },
                { it.printStackTrace() }
                  )

Upvotes: 4

karandeep singh
karandeep singh

Reputation: 2334

This should do.

Observable.just(1)
        .flatMap { 
            return@flatMap Observable.just(it*10)
        }.flatMap { 
            return@flatMap Observable.just(it*20)
        }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
        .subscribe({
            //OnNext
           Log.d("result", "" + it)
        },{
          it.printStackTrace()
            //on error
        },{
            //on complete
        })

Upvotes: 5

Related Questions