Kotlin + RX Observer without Anonymous

0

I'm studying Kotlin Android and RX and just see examples like:

val api = StarWarsService()
api.loadMovies()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        {
                            movie -> movies?.add("${movie.title} - ${movie.epsodeId}")
                        },{
                            e -> e.printStackTrace()
                        },{

                        })

This inside .subscribe is an anonymous Observer with lambda, is that right?

I tried to do something like I already did in java in other studies:

Pessoa p = new Pessoa("João");

        Observable<Pessoa> observable = Observable.just(p);

        Observer<Pessoa> observer = new Observer<Pessoa>() {
            @Override
            public void onCompleted() {
                Log.i("app", "Completado");
            }

            @Override
            public void onError(Throwable e) {
                Log.i("app", "Erro");
            }

            @Override
            public void onNext(Pessoa pessoa) {
                Log.i("app", "onNext" + pessoa.getNome());
            }
        };

        observable.subscribe(observer);

The problem is not lambda, I wanted to create an Observer or Subscribe object and move to .subscribe (observer) the same as the example above Java.

It has like ????

    
asked by anonymous 12.04.2018 / 19:40

1 answer

2

In the first example you showed, three lambdas are being passed (not a Observer ).

Overload with signature is being invoked: subscribe(Consumer<? super T> onNext, Consumer<? super Throwable> onError, Action onComplete) .

To do what you want in Kotlin just create an object expression , like example in the language documentation :

val observable = Observable.just("Hello", "World")
val observer = object : Observer<String> {
  override fun onComplete() {

  }

  override fun onSubscribe(d: Disposable) {

  }

  override fun onNext(t: String) {

  }

  override fun onError(e: Throwable) {

  }
}

observable.subscribe(observer)
    
12.04.2018 / 21:35