片段订阅Observer



我第一次尝试用RxJava实现观察者/订阅者。我得到编译错误:

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。可观测的发现rx。订阅

建议像这样转换到(Observable<String>):

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

确实编译无错误,但给出运行时错误:
. lang。ClassCastException: rx.observers. safessubscriber不能被强制转换为rx。可见

编辑2:我觉得应该是:Subscription loadAndStoreDataObservable = ...

没有人站出来,所以我将把评论汇总成一个答案。

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

相关内容

  • 没有找到相关文章

最新更新