片段订阅观察者

时间:2015-05-21 19:34:17

标签: android observer-pattern rx-java

我正在尝试首次使用RxJava实现Observer / Subscriber。 我收到编译错误:

cannot resolve method subscribe(android.support.v4.app.Fragment) 

在下面的行上。所以我没有正确订阅。 我该怎么做?

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        Fragment myFragment = mTabsPageAdapter.getItem(2);

        Observable<String> loadAndStoreDataObservable = Observable.create(
                new Observable.OnSubscribe<String>() {
                    @Override
                    public void call(Subscriber<? super String> subscriber) {
                        try {           
                            <get data from RESTful service>
                            <write data to SQLite db on device>

                            subscriber.onNext("Done");
                            subscriber.onCompleted();
                        }
                        catch (Exception e) {
                            subscriber.onError(e);
                        }
                    }
                }
        )
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(myFragment); // cannot resolve method subscribe(android.support.v4.app.Fragment)
    }
}

import android.support.v4.app.Fragment;
public class MyFragment extends Fragment implements Observer<String> {

        @Override                         
        public void onNext(String s) {    
            System.out.println(s);        
        }                                 

        @Override                         
        public void onCompleted() {       
        }                                 

        @Override                         
        public void onError(Throwable e) {
        }
}      

编辑:我更改了Vladimir Mironov建议的线路。这似乎是必要的,但还不够。实现它然后我在行上得到编译错误:
不兼容的类型:必需的rx.Observable                      找到rx.Subscription

它建议像(Observable<String>)那样投射:

Observable<String> loadAndStoreDataObservable = (Observable<String>) Observable.create(...)

确实编译没有错误,但是给出了运行时错误:
java.lang.ClassCastException:rx.observers.SafeSubscriber无法强制转换为rx.Observable

编辑2: 我认为它应该是:Subscription loadAndStoreDataObservable = ...

1 个答案:

答案 0 :(得分:3)

没有人在前进,所以我会将评论汇总到一个答案中。

  1. 转换为MyFragment:

    MyFragment myFragment = (MyFragment) mTabsPageAdapter.getItem(2);
    
  2. 将loadAndStoreDataObservable更改为Subscription

    Subscription loadAndStoreDataObservable = ...
    
  3. OnDestroy()中,取消订阅:

    protected void onDestroy() {  
        super.onDestroy();  
        if (loadAndStoreDataObservable != null) {  
           loadAndStoreDataObservable.unsubscribe();  
        }
    }