Search code examples
rx-javarx-java2

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.


Solution

  • 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
    }