I was wondering if the observable is eligible to be garbage collected in this scenario:
fun getObservable() = Observable.interval(500, TimeUnit.Milliseconds)
fun main(args: Array<String>) {
getObservable().subscribe { println(it) }
//Just to be able to observe the output.
Thread.sleep(20*1000)
}
It doesn't stop emitting. But I can't use it to be sure that it will not be GC'd after some time since it may just be that GC isn't triggering in this short span.
My guess is that it should be GC'd. We don't have a reference to the Observable
returned from the getObservable()
function since we can't access it anymore. Calling the function again will give a different new Observable
. Since we can't reach the Observable
itself, the rest of the objects are also unreachable. So, I think all of this can be garbage collected at any random time.
Some of my code in an Android App uses somewhat similar code. And it is an Observable
that I hope will last as long as the Application
. Since, GC will collect any garbage, I don't want my Observable
to be GC'd in the middle of my app. So, please keep that in mind that I'm not looking for answers telling me whether it will be GC'd or not. What I care about is whether it can be GC'd.
Thank you for taking out your time to help me.
EDIT: To make the context clearer, here's the basic idea of the concerned code as I use it in my app.
Repository.kt:
interface Repository {
//Other code.
fun getUserPrefs(): Flowable<UserPreference>
}
MyViewModel.kt:
class MyViewModel(private val repository: Repository): ViewModel() {
init {
repository.getUserPrefs()
.subscribe { //Code with UI state side effects }
}
}
In my app, Repository's implementation will be a singleton.For those not familiar with Android, just know that ViewModel's can last for pretty long time. It's work is basically to be responsible for managing UI state.