Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rxjava add items after observable was created

I just started using rxjava and I got stuck. Maybe I'm not using rxjava in the right way, but I need to add items to an Observable after it was created. So I understand that You can just call Observable.just("Some", "Items") and the subscribers will receive them, but what if I have an async task and I need to add some more items at later time when the task is finished? I couldn't find anything like Observable.addItems("Some", "More", "Items")

like image 928
Jelly Avatar asked Mar 07 '15 10:03

Jelly


2 Answers

What you probably need is Subject - http://reactivex.io/documentation/subject.html

It is an object that is both Observer and Observable, so you can subscribe to it and emit new items. For example :

PublishSubject<String> subject = PublishSubject.create();
subject.subscribe(System.out::println);
subject.onNext("Item1");
subject.onNext("Item2");
like image 181
krp Avatar answered Oct 18 '22 19:10

krp


It is useful to note that PublishSubject does not cache items. For example if the above code was the following, Item1 would not have been printed since the subject was not yet subscribed. PublishSubject<String> subject = PublishSubject.create(); subject.onNext("Item1"); subject.subscribe(System.out::println); subject.onNext("Item2");

Use ReplaySubject for caching. It would be helpful to read this

like image 2
shobhitdutia Avatar answered Oct 18 '22 18:10

shobhitdutia