6
    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()
                }
            })
s-hunter
  • 24,172
  • 16
  • 88
  • 130

2 Answers2

5

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
        })
karandeep singh
  • 2,294
  • 1
  • 15
  • 22
4

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() }
                  )
Antek
  • 721
  • 1
  • 4
  • 27