Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the shareReplay function working?

I have read RxSwift/ShareReplayScope.swift file, but a little difficult to understand.

public func share(replay: Int = 0, scope: SubjectLifetimeScope = .whileConnected)
        -> Observable<E> {
        switch scope {
        case .forever:
            switch replay {
            case 0: return self.multicast(PublishSubject()).refCount()
            default: return self.multicast(ReplaySubject.create(bufferSize: replay)).refCount()
            }
        case .whileConnected:
            switch replay {
            case 0: return ShareWhileConnected(source: self.asObservable())
            case 1: return ShareReplay1WhileConnected(source: self.asObservable())
            default: return self.multicast(makeSubject: { ReplaySubject.create(bufferSize: replay) }).refCount()
            }
        }
    }

0,1 and default,what is the difference? why separate 1 from defalut?

 override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E {
        _lock.lock()

        let connection = _synchronized_subscribe(observer)
        let count = connection._observers.count
        let disposable = connection._synchronized_subscribe(observer)

        _lock.unlock()

        if count == 0 {
            connection.connect()
        }

        return disposable
    }

how the lock work, and the most difficult is this function. how the blocked obserables connect to their observers correctly.

like image 558
Tom Avatar asked Jan 08 '18 08:01

Tom


1 Answers

Below you get the information about shareReplay function.

share()

As you know share function shares the subscription of Observable. So that you don't need to create multiple observable instances every time.

Simply create one observable and share replay. it will allow to perform next operation within this sharable observable. i.e filter(), subscribe(), etc..

But the problem with share() is, it is not provide values before subscription.

shareReplay()

Where shareReplay() keeps a buffer of the last few emitted values and can provide them to new observers upon subscription.

like image 125
Jaydeep Vora Avatar answered Oct 01 '22 19:10

Jaydeep Vora