2016-08-03 133 views
2

我想學RxAndroid但我已經提到了行operationObservable.subscribe(new Subscriber() {和另一行.create(new Observable.OnSubscribe() {中的錯誤。這是爲什麼?RxAndroid:類必須聲明爲抽象或實現抽象方法的錯誤

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

您應泛型方法

 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(); 
      } 
     }); 

希望這有助於更換使用它。

+0

這有助於看起來比我的想法更漂亮。 – y07k2

+0

很高興幫助你:) – Sanjeev

1

需要改變

public void call(Subscriber subscriber) {

public void call(Object o) {

,然後澆鑄的參數Subscriber的方法內。

相關問題