简体   繁体   中英

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.

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. If you must put the reviews function in a class, the DB_REVIEWS class is as good as any I guess.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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