WishIHadThreeGuns
WishIHadThreeGuns

Reputation: 1469

Return BehaviourSubject in RXSwift

I get a HTML page from my NodeJS instance with the signature:

public func requestHTMLPage(_ page: String) -> Observable<String?> 

but I've got some cached HTML pages so want to return them.

I'd like to return my cached page

if let cachedPage = cachedPage {
    return BehaviorSubject<String?>(value: data)
}

but unfortunately it does not tell my subscribers that the data is returned.

I've used the following awful solution:

if let cachedPage = cachedPage {
    observer.onNext(data)
    return BehaviorSubject<String?>(value: data)
}

as I want to tell my observer we have the data, but also I want to return as we are at the end of this path of execution.

How can I return and give the type Observable after I have made my observer.onNext, or how can I return with just observer.onNext?

Upvotes: 0

Views: 77

Answers (1)

Val&#233;rian
Val&#233;rian

Reputation: 1118

I'm not sure why you try to use a Subject here, you probably simple need to use Observable.create:

public func requestHTMLPage(_ page: String) -> Observable<String?> {
  return Observable.create { observer in
    if cachedPage = self.cache[page] {
      observer.onNext(cachedPage)
      observer.onCompleted()
      return Disposables.create()
    } else {
      /* whatever you use to fetch the data in a reactive way */
      return self.service.rx.request(page).subscribe(observer)
    }
  }
}

Depending on where this code is, pay attention to retain cycles.

Upvotes: 1

Related Questions