Rxjava behaviorsubject remove / clear value

I have an application that uses BehaviorSubject

both memory for some value. This value is set when the application starts, based on the result of the REST API request, if the user is logged in, or during the user's logon. But when the user logs out, the BehaviorSubject retains the old value. Is there a way to clean up BehaviorSubject

and make it have hasValue()

as false on demand?

+4


source to share


2 answers


The short answer is no.

Once the subject receives at least one value hasValue

, it will always return true. A common trick in such cases is to have a wrapping class. Here's an example with Optional

:



Subject subject = BehaviorSubject.<Optional<String>>create()
// add
subject.accept(Optional.of("Hello"))
// "clear" value
subject.accept(Optional.empty())

// check
subject.value.isPresent()

      

+1


source


Another possible way to do this is to create BehaviorSubject

from a 1-item list. If you want to remove it, just do:

val subject: BehaviorSubject<List<YourObject>> = BehaviorSubject.create()
subject.onNext(emptyList())

      



But I would support the idea that this kluge is wrong. There should be a more elegant solution.

0


source







All Articles