hoc nguyen
hoc nguyen

Reputation: 73

Is Observable object released automatically RxAndroid

I have a function that creates Observable:

void getData() {
   Observable.create(emitter -> {
      // call webservice
      .......
      emitter.onNext(myData);
   }).subscribe(data -> {
      // Process data here
   });
}

I don't want to use Disposable here. I think the observable is local variable, so it will be released after the function is done. Is the observable released automatically after I call getData() function?

Upvotes: 0

Views: 598

Answers (2)

nhoxbypass
nhoxbypass

Reputation: 10152

Observable will automatically dispose they called onComplete() or onError()

Ex: You have a method to load exactly data from 10 files Observable<String> loadFiles() which return Observable.create(). Then every time you want to emit value you call e.onNext(), after count 10 times you will call e.onComplete() to mark that your Observable has finish it's work, then it will auto dispose.

You only need to call dispose() method to indicate that the Subscriber is no longer interested in any of the Observables it is currently subscribed to. Those Observables can then (if they have no other interested observers) choose to stop generating new items to emit.

Call dispose() when activity stopped to make sure that no more emission will come after that. So it's a good practice because it can prevent memory leaks and waste of resources, network calls.

Upvotes: 1

Bishoy Kamel
Bishoy Kamel

Reputation: 2355

Observables do not dispose them-selfs.

It's a good practice to dispose your observable to avoid memory leaks and crashes of your app.

you either use disposable.dispose() or compositeSubscribtion.clear().

I have made a simple test and after I exited the app(back btn) observable continued to emit data.

 btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Observable.create(emitter -> {
                for (; ; ) {
                    emitter.onNext("data");
                    Thread.sleep(3000);
                }

            }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).
                    subscribe(data -> {
                        Log.d(tag, (String) data);

                    });

        }
    });

OUTPUT :

onStart() is called 
onResume() is called 
data
data
onPause() is called
onStop() is called
data 
data

Upvotes: 0

Related Questions