LightYearsBehind
LightYearsBehind

Reputation: 1804

How to build a togglable iterable stream in RxJava?

I would like to build a togglable iterable stream (Observable<List<T>>) as follows:

  1. When subscribed, emit an empty iterable (eg. List)
  2. When an input is received (PublishSubject?), add it to the iterable and emit it.
  3. When an input is received again, add it to the iterable (if not exist) or remove it from the iterable if existed, then emit it.
  4. Repeat step 3.

Is this easy to achieve with RxJava?

Pardon if my question is not clear, I am new to reactive programming.

Upvotes: 0

Views: 66

Answers (1)

gpunto
gpunto

Reputation: 2852

I think you can do it with a single Subject + scan operator:

val subject = PublishSubject.create<Int>()
subject.scan(mutableListOf<Int>()) { list, item ->
    list += item
    list
}

Upvotes: 1

Related Questions