Kotlin + RX Observer without Anonymous

Asked

Viewed 82 times

0

I’m studying Kotlin Android and RX and I only 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()
                        },{

                        })

That inside the . subscribe is an Observer anonimo with lambda, that’s right?

I tried to do something like I 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 pass to . subscribe(Observer) the same in the example above Java.

Has as????

1 answer

2


In the first example you showed, there are three past (and not one Observer).

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

To do what you want in Kotlin just create a Object Expression, as exemplified in 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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.