Kevin Bryan
Kevin Bryan

Reputation: 1858

How to dispose from another class?

I have a main class that implements ApplicationLister and a bunch of other classes that doesn't implement anything, what I have in mind is this.

//I create a method for is disposing on my other classes
 public void disposable(){
  //things to dispose
}

// and then call the method on the main class

public void dispose(){
  classObj.disposable();
}

Is my idea any good? and also how do I know all the classes/methods that are disposable.

Upvotes: 1

Views: 4162

Answers (1)

bemeyer
bemeyer

Reputation: 6231

There is an interface in libgdx which foces you to implement a dispose method. It allows you to put all disposables into a list and dispose them at the end. In the end it is not a bad idea to implement a dispose at every object which holds resources like for example the Assetmanager or a Screen implementation. But you do not need it for everything since the object does get distroyed when the garbage collector is running over it. You can not delete a object on purpose.

Take a look into the Disposable Interface and the classes which implement this to know which classes you can dispose. As already mentioned it is used for classes which holds resources.

A simple class would look like this:

public class Foo implements Disposable{
    @override
    public void dispose()
    {
        //release the resources used here like textures and so on
    }
}

It does exactly look like your approach but you could add all disposables into a list to dispose when the game is closed:

ArrayList<Disposable> disposables = new ArrayList<Disposable>();
Foo myFoo = new Foo();
disposables.add(myFoo);

//game is running
//....
//
for(Disposable d : myFoo)
{
    d.dispose();
}
//end of the main

Try to use the Libgdx util classes.

Further reading for knowledge about disposing and why: Memory Management from libgdx Wiki

One importand sentense from here is:

[...] implement a common Disposable interface which indicates that instances of this class need to be disposed of manually at the end of the life-time.

Upvotes: 1

Related Questions