Al Lelopath Al Lelopath - 1 year ago 206
Android Question

Fragment subscribe to Observer

I'm trying to implement an Observer/Subscriber with RxJava for the first time.
I get the compile error:

cannot resolve method subscribe(

on the line indicated below. So I'm not subscribing correctly.
How do I do this?

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

Fragment myFragment = mTabsPageAdapter.getItem(2);

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

catch (Exception e) {
.subscribe(myFragment); // cannot resolve method subscribe(

public class MyFragment extends Fragment implements Observer<String> {

public void onNext(String s) {

public void onCompleted() {

public void onError(Throwable e) {

Edit: I changed the line suggested by Vladimir Mironov. This seems to be necessary but not sufficient. Implementing it I then get a compile error on the line after that:

Incompatible types: Required rx.Observable
Found rx.Subscription

It suggests casting to
like so:

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

which does indeed compile error-free, but gives the runtime error:

java.lang.ClassCastException: rx.observers.SafeSubscriber cannot be cast to rx.Observable

Edit 2:
I think it should be:
Subscription loadAndStoreDataObservable = ...

Answer Source

No one is stepping forward, so I'll aggregate the comments into an answer.

  1. Cast to MyFragment:

    MyFragment myFragment = (MyFragment) mTabsPageAdapter.getItem(2);
  2. Change loadAndStoreDataObservable to be a Subscription

    Subscription loadAndStoreDataObservable = ...
  3. In OnDestroy(), unsubscribe:

    protected void onDestroy() {  
        if (loadAndStoreDataObservable != null) {  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download