RxAndroid:类必须声明为abstract或实现抽象方法错误

时间:2016-08-03 11:11:44

标签: java android rx-java rx-android

我正在尝试学习RxAndroid但是,我在第operationObservable.subscribe(new Subscriber() {行和第.create(new Observable.OnSubscribe() {行中提到了错误。那是为什么?

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
}

2 个答案:

答案 0 :(得分:2)

你应该以通用的方式使用它

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

应替换为

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

希望这有帮助。

答案 1 :(得分:1)

需要更改

public void call(Subscriber subscriber) {

public void call(Object o) {

然后将参数转换为方法内的Subscriber