How to set default value in BehaviourSubject

馋奶兔 提交于 2020-08-25 07:43:43

问题


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?


回答1:


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)



回答2:


When Subscribing to this Subject you can use Start with Operator

widgetStateEmitter.startWith(HIDDEN)
//continue your chain



回答3:


In your constructor or onCreate (or similar) just call widgetStateEmitter.onNext(HIDDEN)



来源:https://stackoverflow.com/questions/52050555/how-to-set-default-value-in-behavioursubject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!