Reputation: 2634
While I think I've got a handle on the basics of how to use RxJava, I'm having trouble using the Observer pattern.
Basically, what I want to do is have a static List
of objects that I can monitor, and use additions to the list to submit this data to a webservice.
My approach so far has to just been create a static List<Object>
and a static Observable<Object>
. This observable is created by just doing a
observable = Observable.from(listOfObjects);
Then, I have my upload logic inside of a .subscribe()
call. This would work if I had the List
all set up ahead of time, but I want to populate it here and there at runtime. This will still work if I call .subscribe()
again, but it feels like I am doing something wrong by doing that. I thought I could get the existing subscription to just act on any new items emitted from the observable, but nothing seems to be happening when I add to the list.
Any insight on a better/correct approach is appreciated.
Upvotes: 2
Views: 1915
Reputation: 11515
Observable.from(listOfObjects)
will create a new observable that will emit each of list's objects. You can write Observable.just(1, 2, 3, 4)
too. It's the same thing.
So, if you add an object into your list, the Observable
won't be notified.
You can create a custom list that will notify your Observable
from a new added item. You will see a very close solution to his in topic : How can I create an Observer over a dynamic list in RxJava?
But, you can ride of your list and maybe use a Subject
instead ? Instead of adding object to your list, just call theSubject.onNext
method.
Please note that you only be notified when item will be added. You won't be notified when items are removed. If you want to, your Observable
shouldn't emit added item but item, with an associated state : new Added<Object>(item)
, new Removed<Object>(item)
for example.
Upvotes: 2