I have an Observable which is executing a network request and emits the data. I have multiple subscribers for this Observable and since I don't want to re-execute the network request for each new subcribers, I'm multicasting the Observable using the replay().autoConnect()
operator. This works perfect and for my second subscriber is immediately getting the data without re executing the network request, since the replay
operator caches the old result. But the problem is, I don't want this cached data to be modified. For example , some of the subscribers make some modifications to the result , Which I don't want to get reflected in first place. So, basically I don't want to duplicate the network request , at the same time I need a deep copy of the cached data as well. Is it possible using any operator? Or is there any Rx solution for this problem?
I think my question is clear.
I am adding a sample code snippet which shows the issue.
public class Person {
String name;
public Person(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
private List<Person> getPersonList() {
List<Person> persons = new ArrayList<>();
persons.add(new Person("Person A"));
persons.add(new Person("Person B"));
persons.add(new Person("Person C"));
return persons;
}
Observable<List<Person>> netWorkCall = Observable.fromCallable(this::getPersonList)
.replay()
.autoConnect();
// first subscription
netWorkCall.subscribe(persons -> {
for (Person person : persons) {
System.out.println(person);
}
// output is as follows
// Person A
// Person B
// Person C
});
// second subscription, whic does some modification
netWorkCall
.flatMap(new Function<List<Person>, ObservableSource<List<Person>>>() {
@Override
public ObservableSource<List<Person>> apply(@NonNull List<Person> persons) throws Exception {
return Observable.fromCallable(() -> persons);
}
})
.subscribe(persons -> {
for (int i = 0; i < persons.size(); i++) {
Person person = persons.get(i);
person.name = "Person " + i;
System.out.println(person);
}
// output is as follows
// Person 0
// Person 1
// Person 2
});
// third subscription , again calls the replayed Observable
netWorkCall.subscribe(persons -> {
for (Person person : persons) {
System.out.println(person);
}
// Here I need output is as follows
// Person A
// Person B
// Person C
// But what I get is
// Person 0
// Person 1
// Person 2
});