gpt4 book ai didi

garbage-collection - 如果我删除对我订阅的 observable 的所有显式引用,它会被垃圾收集吗?

转载 作者:行者123 更新时间:2023-12-04 21:36:54 25 4
gpt4 key购买 nike

我有一个从远程服务器发出响应的 observable。我通过一个将结果填充到缓存中的操作来订阅它。

  • 一旦我自己对原始 observable 的所有显式引用都消失了,是否存在上述副作用操作无法执行的危险?
  • 更一般地说,作为 rxjava 用户,我需要了解关于垃圾收集和 rxjava 的哪些信息?

  • 奖励:这是一个 clojure 实验,展示了当有订阅者时,一个 observable 被保留,或者它只是显示了订阅 observable 的副作用。

    (ns adhoc.rx-gc
    "Testing behavior of RxJava and garbage collection."
    (:require [rx.lang.clojure.core :as rx])
    (:import (java.lang.ref WeakReference)
    (java.util.concurrent TimeUnit)
    (rx Observable)))

    (defn test-gc
    [sub?]
    ;; Hold source in an atom to be sure we can wipe references to it
    ;; and not worry about lexical scope.
    (let [a-src (atom (.delay (rx/return "hello") 5 TimeUnit/SECONDS))
    w-src (WeakReference. @a-src)]
    (when sub?
    (rx/subscribe @a-src
    #(do (println "Value:" %)
    (println "On-update ref:" (.get w-src)))))
    (reset! a-src nil)
    (System/gc)
    (println "After-gc ref:" (.get w-src))))

    (comment
    (test-gc false)
    ;; After-gc ref: nil

    (test-gc true)
    ;; After-gc ref: #<Observable rx.Observable@21863f3b>
    ;; Value: hello
    ;; On-update ref: #<Observable rx.Observable@21863f3b>
    )

    最佳答案

    Once all of my own explicit references to the original observable are gone, is there danger that the side-effecting action mentioned above will fail to act?



    这取决于。如果您使用 Scheduler , 可能有一些对您的 Observable 的隐式引用在 Scheduler 的某个线程中.

    More generally, what do I need to know as an rxjava user about garbage collection and rxjava?



    请务必调用 Subsscription.unsubscribe当你想释放资源,永远不要忽视 Subscription s 由 Observable.subscribe 返回.

    关于garbage-collection - 如果我删除对我订阅的 observable 的所有显式引用,它会被垃圾收集吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35564397/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com