Do I need to free/release Observable object after I use it?

后端 未结 2 1076
终归单人心
终归单人心 2021-01-27 10:55

Do I need to free/release Observable object after I use it in case Observable object is not garbaged by GC? I didn\'t find any article to mention it. Is Observable object garbag

2条回答
  •  孤街浪徒
    2021-01-27 11:23

    Observable doesn't automatically "free" anything, but give you the tools to do it.
    there are some aspects of resource management with Observable:

    • Releasing any resource associated with the 'Producer' - the resource that generates events, this resource can be anything from IO related resource - network query, some hardware/sensor related events, DB triggers; UI related resource - clicks, scrolling etc.
      That's needs to manage by you with the framework that Observable gives you, it's the Cancellable/Disposable components, the framework guarantees that this events will be triggered at the appropriate time - when Observable completes, when unsubscribing/disposing Observable. but it's up to you to trigger the appropriate logic - cancelling the network query, shutdown/release/close IO resource, unregister from your Listener etc, all depends on your Producer logic
    • Disposing/unsubscribing the Subscriber from the Obesrvable explicitly when your resource is no longer needed - while the Observable gives you the framework to clear resources, it's up to you to trigger it at explicit times. while Observable will trigger it automatically when Observable completes, that sometimes too late and you want to cancel it before (i.e. network query ) and with other cases your Observable might be of infinite items, think of DB inserts listener, clicks events or any other listener, with this cases the resource will be held up until you will explicitly release it by disposing the Observable.
    • It is also important to untie (dispose) the connection between the Observable and the Subscriber, for preventing memory leaks, as the Subscriber might hold hard reference to wrapping classes and thus will be leaked by the Observable. (classic with UI components, where subscriber reference some UI class and subscribe to some static nature Observable)
    • It worth noting that disposing Observable will trigger Thread interrupt to the Producer subscription thread. so in case you have IO operation there, you might get InterruptedException.

提交回复
热议问题