Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any difference between "Subject.asObservable()" and the subject itself "Subject"?

If a Subject inherit from Observable, whats the difference the next options based on any Subject like:

private val locationSubject: ReplaySubject<Location> = ReplaySubject.create<Location>()

1. Returning a subject itself as Observable

fun getLocations(): Observable<Location> = locationSubject

2. Returning subject.asObservable().

fun getLocations(): Observable<Location> = locationSubject.asObservable()
like image 886
Daniel Gomez Rico Avatar asked Feb 05 '23 11:02

Daniel Gomez Rico


1 Answers

if you look at the implementation of .asObservable you will see it lifts the observable with an operator that does nothing. This effectively just wraps your subject in an observable which makes it impossible for the consuming code to cast it back to a subject.

asObservable is a defense mechanism to hide implementation details and not much else.

like image 121
TrevJonez Avatar answered Feb 07 '23 12:02

TrevJonez