Solved LibGDX List of Disposable objects

Hello, I’m trying to find out if I should be adding many disposable objects to a list, then when on closing, I can just loop through the array with .dispose(); to close everything.
Does something like this actually dispose of every object in an array, the same way as calling .dispose() on the item itself would?

For example:


BitmapFont bf = new BitmapFont();
bf.dispose();

This is what I’m trying:


List<Disposable> disposable = new ArrayList<>();

Sprite sprite;

public Menu(Sprite sprite) {
    this.sprite = sprite;
    disposable.add(this.sprite.getTexture());
}

public void disposeAll() {
    for(Disposable d:disposable)
        d.dispose();
}

It gives me no errors because all of the .dispose() capable objects implement Disposable.
I just can’t figure out if it is actually closing or not :s

Thanks muchly!

Try calling a method from one of the Disposable objects after the disposeAll() method is called. If it’s disposed, it should throw an error. If it’s not, it’ll work (hint: you don’t want it to work).

Well the sprite I was testing it on turned black, blocking out everything behind it. So yah, I guess it does work ^^ Damn, so simple lol. The black texture it left behind was what threw me the most.
It doesn’t throw an error.

I think it does throw an error, just a hidden OpenGL one about null texture. Anyway, I’m glad I could help.

When your app exits, everything is disposed. You only need to dispose things explicitly if you need them to be disposed without exiting the app. Eg, maybe you have separate screens and want to unload all the stuff from one screen before you show another. This could make sense if the screens each had a huge map with screen specific textures, etc.

Does this mean disposing all things Disposable when the app exits is unnecessary?

Definitely, yes. Don’t do stuff you don’t have to do.

Ah right, that was another thing I was kinda curious about. I need to close everything when I’m switching scenes. So, being able to have a super class, add everything I setup in its sub classes to a list for later disposing of is pretty nice. I can’t just add everything that is declared in the super class, to a disposable method, as not everything in the super class will actually be instantiated you see.

Thanks all :slight_smile:

Questions were completely answered.

You might check out AssetManager. When you leave scene A, first add all assets from scene B to the AssetManager, then remove all assets scene A used. The result will be that any assets used in both scene will stay loaded, any assets from A that are no longer needed are disposed, and any assets for B that weren’t loaded are loaded. Also, loading happens on a separately thread as much as possible, allowing you to have a progress bar.

Oh gosh. That’s now gonna be a hard habit for me to break :frowning: