Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default value in BehaviourSubject

Probably a noob question. How do I set a default value to a BehaviourSubject.

I have an enum with 2 different values

enum class WidgetState {
    HIDDEN,
    VISIBLE
}

And a behaviour subject which emits the states

val widgetStateEmitter: BehaviorSubject<WidgetState> = BehaviorSubject.create()

My emitter starts emitting when the view logic is written. However it's HIDDEN by default. How do I set the default value as WidgetState.HIDDEN to my emitter widgetStateEmitter?

like image 740
capt.swag Avatar asked Dec 11 '22 05:12

capt.swag


1 Answers

There's a static BehaviorSubject.createDefault(T defaultValue) factory method that allows to set the initial value.

The Javadoc for the defaultValue parameter says:

defaultValue - the item that will be emitted first to any Observer as long as the BehaviorSubject has not yet observed any items from its source Observable

So you just have to create your BehaviorSubject as follows:

val widgetStateEmitter: BehaviorSubject<WidgetState> = 
        BehaviorSubject.createDefault(HIDDEN)
like image 125
Robby Cornelissen Avatar answered Dec 12 '22 18:12

Robby Cornelissen