Issue
Perhaps I don't understand how to use Realm with Observables properly properly but I seem to be getting a Realm memory leak when I create an Observable from a Realm Where and Subscribe to it. I close the Realm in onDestroy() and unsubscribe from the Observable in onPause(). However, if I add and back out of the following Fragment a few times (it is added to the BackStack and removed on back press):
public class RealmFragment extends android.support.v4.app.Fragment {
private Realm mRealm;
private Subscription mSubscription;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_realm, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRealm = Realm.getDefaultInstance();
mSubscription = mRealm.where(Person.class)
.findAllAsync()
.asObservable()
.subscribe(new Action1<RealmResults<Person>>() {
@Override
public void call(RealmResults<Person> persons) {
Log.d("RXREALM", "OnNext called");
}
});
}
@Override
public void onPause() {
super.onPause();
mSubscription.unsubscribe();
}
@Override
public void onDestroy() {
super.onDestroy();
mRealm.close();
}
}
I've noticed if I do a couple GC's then a heap dump in Android studio there is multiple instances of Realm and RealmResult equal to the number of times I started the Fragment. I keep no reference to them anywhere. There is no reference to the RealmFragment after the last time I've left it.
I've noticed if I DO NOT unsubscribe from the Where Subscription the count of Realm objects doesn't increase. The count of RealmResults still increases.
I made an empty project to test this. RxJava and Realm are up-to-date. Any clarification regarding why this happens or how Realm manages Observables is appreciated. The whole empty project can be found here while I investigate the issue: https://github.com/willjgriff/android-realm-leak
Solution
Realms code for generating Observables are here: https://github.com/realm/realm-java/blob/master/realm/realm-library/src/main/java/io/realm/rx/RealmObservableFactory.java
As long as you don't unsubscribe an observable, Realm will keep a strong reference to it, but it should release that reference when you unsubscribe.
But without Without more context about your code, it is hard to tell exactly what is going on. Can you post an entire example.
Answered By - Christian Melchior
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.