# .hide() your Subjects - RxJava tip

DevFeed: [.hide() your Subjects - RxJava tip](<https://devfeed.tech/articles/hide-your-subjects-rxjava-tip-25321.md>)

Original publisher: [Read original article](<https://kau.sh/blog/rx-tip-hide-your-subjects/>)

Author: Kaushik Gopal

Published: 2019-03-30T07:00:00Z

Content type: tutorial

Language: en

Sources: [Kaushik Gopal's Site](<https://devfeed.tech/sources/kaushik-gopal-s-site.md>)

Topics: [RxJava](<https://devfeed.tech/topics/rxjava.md>), [Android](<https://devfeed.tech/topics/android.md>)

Tags: [android](<https://devfeed.tech/tags/android.md>), [rxjava](<https://devfeed.tech/tags/rxjava.md>)

## AI overview

This tutorial explains RxJava's .hide() operator. It shows how hiding a Subject can expose an Observable instead, preventing an Android Activity from modifying ViewModel state, and introduces its relationship to operator fusion.

## Source excerpt

A not so well known api in RxJava is the .hide() operator. When does one use the hide operator in Rx? ## From the docs: Hides the identity of this Observable and its Disposable. Allows hiding extra features such as Subject's Observer methods or preventing certain identity-based optimizations (fusion). there are a lot of complex operations that take place internally in RxJava (like internal queue creation, worker instantiation + release, numerous atomic variables being created and modified.) If this doesn't make too much sense, let's look at examples to make this clear. Consider a typical MVVM usecase: class MyAndroidVm : ViewModel() { private val outputSubject = BehaviorSubject.createOnDefault(initialViewState()) init { Observable.just(service.pollModelData()) .map { // ... do something with the Event that pipes a result // or view state eventually } .subscribe { viewState -> outputSubject.onNext(viewState) } } fun listenToViewState(): BehaviorSubject<ViewState> { return outputSubject } // ... } In this sample code, the ViewState is basically what the Activity would consume. So within the ViewModel, we pipe the data into a Subject, which is then exposed to the Activity like so: class MyAndroidActivity: Activity { // ... override fun onResume() { viewModel.listenToViewState() .observeOn(AndroidSchedulers.mainThread()) .subscribe { viewState -> // bind Android Views and ViewState object } } } This is all great, however the trouble with exposing a Subject is that it allows the activity to modify the internal state of the Behavior Subject from the outside. This is non-ideal as we only want the ViewModel controlling this. class MyAndroidActivity: Activity { // ... override fun onResume() { viewModel.listenToViewState() .onNext(badViewState()) // we want to avoid this .observeOn(AndroidSchedulers.mainThread()) .subscribe { viewState -> // bind Android Views and ViewState object } } } So we don't want to expose the Subject directly. It would make more sense instead to just