y07k2 y07k2 - 4 months ago 25
Android Question

RxAndroid: Class must either be declared abstract or implement abstract method error

I'm trying to learn

RxAndroid
but, I've got mentioned error in line
operationObservable.subscribe(new Subscriber() {
and another in line
.create(new Observable.OnSubscribe() {
. Why is that?

import android.app.Activity;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import rx.Observable;
import rx.Subscriber;

public class MainActivity extends AppCompatActivity {
Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final Activity activity = this;

button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
v.setEnabled(false);
operationObservable.subscribe(new Subscriber() {
@Override
public void onCompleted() {
v.setEnabled(true);
}

@Override
public void onError(Throwable e) {}

@Override
public void onNext(String value) {
Snackbar.make(findViewById(android.R.id.content), value, Snackbar.LENGTH_LONG).show();
}
});
}
});
}

public String longRunningOperation() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// error
}
return "Complete!";
}

final Observable operationObservable = Observable
.create(new Observable.OnSubscribe() {
@Override
public void call(Subscriber subscriber) {
subscriber.onNext(longRunningOperation());
subscriber.onCompleted();
}
});
// .subscribeOn(Schedulers.io()) // subscribeOn the I/O thread
// .observeOn(AndroidSchedulers.mainThread()); // observeOn the UI Thread
}

Answer

You shall use it in generics way

        new Observable.OnSubscribe() {
            @Override
            public void call(Subscriber subscriber) {
                subscriber.onNext(longRunningOperation());
                subscriber.onCompleted();
            }
        });

shall be replaced by

        new Observable.OnSubscribe<Subscriber>() {
            @Override
            public void call(Subscriber subscriber) {
                subscriber.onNext(longRunningOperation());
                subscriber.onCompleted();
            }
        });

Hope this helps.