naman14 / TimberX

Material theme music player that works across all form factors (phones, wear, auto, cast, assistant) and uses latest tools (Kotlin, Architecture components, Room, Databinding)

Home Page:https://namand.in

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

doAsync classes will leak

afollestad opened this issue · comments

Stuff like:

class doAsync(val handler: () -> Unit) : AsyncTask<Void, Void, Void>() {
    override fun doInBackground(vararg params: Void?): Void? {
        handler()
        return null
    }
}

Will very likely cause a memory leak if the task doesn't end before the app is minimized. It's better to use scoped coroutines or RxJava.

Or just run them inside an AAC ViewModel, and post the value back by updating a LiveData which is observed in the Fragment using the view lifecycle owner.

@Zhuinden that could help but anything used in the lamba can still leak, even with a view model.

Coroutines come with the advantage of being able to stop execution completely. You can scope them to your view models as well.

Maybe we should just use an EventBus from coroutines executed in the GlobalScope ❤️

Aha, that's kind of an anti pattern as well IMO 😁 I'm very opinionated on architecture, coming from @square

Ideally the coroutines should be attached to a view model so they stop when their respective Fragment or Activity does. And generally I would favor RxJava or dependency injected classes over an Event Bus.

@afollestad Any opinions about when the task needs to be executed from a service. Like when there is no activity attached and user clicks on next song from notification. How to properly update the session state and other tasks in background.

Ah yeah I would definitely use a background service that is foregrounded for that, similar to how MNML handles its recording notification

I think it depends if you really want to cancel a task just because you navigated away from a screen.

Sometimes you do want it to finish.

Sometimes not.

Eh, Google explicitly says to avoid AsyncTask because it leaks. Android Studio warns you about all async tasks in this project, especially nested ones.

Almost all code you would put in the lambda for this app's use case could be variables that could end up leaking. Especially the one which posts a result. That's unnecessary data being kept in memory.

Things that should be long running after your Activities needs to be in a Service or JobScheduler job.

Here's phase 1, which enables coroutines in view models and uses them: #17