简体   繁体   English

RxSwift) 订阅一个 observable 两次不工作

[英]RxSwift) Subscribing one observable two time not working

Observable Codes可观察代码

private let reviewPublish = PublishSubject<Review>()

var review$: Observable<Review> {
    return reviewPublish.asObservable()
}

Publishing Code发布代码

DB_REVIEWS.observe(.value){ snapShot in
    for child in snapShot.children {
        guard let snap = child as? DataSnapshot else { return }
        guard let data = snap.value as? [String: Any] else { return }
                
        var review = Review()
        review = self.changeDictionaryToReview(data, snap.key)
        self.reviewPublish.onNext(review)
   }
   self.reviewPublish.onCompleted()
} 

Subscribe Code订阅码

DBUtil.shared.review$.subscribe(onNext: {
    self.reviews.append($0)
}).disposed(by: self.disposeBag)

Question

I subscribed when the app was launched.我在应用程序启动时订阅了。 So, getting reviews from the database and storing them in an array succeeded.因此,从数据库中获取评论并将它们存储在数组中是成功的。 However, it cannot be reflected in real time.但是,它无法实时反映。 After the app is launched, if the user adds a new review, it is not reflected.应用启动后,如果用户添加了新的评论,则不会反映。 "self.reviewPublish.onNext(review)" works, but subscribe code in viewController not work. “self.reviewPublish.onNext(review)”有效,但在viewController 中订阅代码无效。

any idea?任何的想法?

Based on the information you gave in the question so far, I would expect the code to look like this rather than what you have:根据您目前在问题中提供的信息,我希望代码看起来像这样,而不是您拥有的:

extension Review {
    init(_ data: [String : Any], _ key: String) {
        // store what you need to here
    }
}

func reviews() -> Observable<[Review]> {
    return Observable.create { observer in
        DB_REVIEWS.observe(.value) { snapShot in
            let reviews = snapShot.children.compactMap { (child) -> Review? in
                guard let snap = child as? DataSnapshot else { return nil }
                guard let data = snap.value as? [String: Any] else { return nil }
                return Review(data, snap.key)
            }
            observer.onNext(reviews)
        }
        return Disposables.create { /* stop observing here */ }
    }
}

There is no reason at all it add a Publisher to the system.完全没有理由将发布者添加到系统中。 I expect there is some way to cancel the observation so put that in the Disposables.create function.我希望有某种方法可以取消观察,因此将其放入 Disposables.create 函数中。 If you must put the reviews function in a class, the DB_REVIEWS class is as good as any I guess.如果您必须将reviews功能放在一个类中,那么 DB_REVIEWS 类和我猜的一样好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM