Create infinite repeatable Observable from array - reactive-programming

Let's say I have an array items
I know I can create an observable from this array using
Rx.Observable.fromArray(items)
How do I create a lazily infinitely repeating observable from this (i.e.: repeating the items as long as they are being requested)?
Tried
Rx.Observable.fromArray(items).repeat()
But this doesn't execute lazily and therefor locks up the browser.

You cannot do this with an Observable. You way want to look at using an Enumerable.
The Enumerable flavor of Reactive Extensions is known as Interective Extensions.

I'm still a newcomer to RxJS, so perhaps what I am proposing is complete madness, but could something along the lines of the following work for this?
var items = [1, 2, 3, 4, 5];
var infiniteSource = Rx.Observable.from(items)
.map(function (x) { return Rx.Observable.return(x).delay(1000); })
.concatAll()
.doWhile(function(_) { return true; /* i.e. never end */ });
infiniteSource.subscribe(function(x) { console.log(x); });
I have an example here: http://ctrlplusb.jsbin.com/sihewo/edit?js,console
The delay is put in there so as not to flood the console. In terms of the "until no longer needed part" perhaps an unsubscribe or other mechanism can be injected into the doWhile?

Related

Are lists ensured to be processed in order by a for loop?

In a Flutter application, is the order of a list always ensured?
List<MyClass> myObjects;
// ... many add operations
int i = 0;
for(MyClass myObject in myObjects) {
assert(myObject == myObjects[i]); // will it always go through?
i++;
}
If not, what is the most efficient way to ensure a list is maintained and processed in the right order?
Yes. for-in in Dart works on Iterable objects. (It is not like for-in in JavaScript which iterates over object properties, which could be in some indeterminate order.)
From the List documentation:
Lists are Iterable. Iteration occurs over values in index order.

Make iterations of a loop sequentially in Mutiny

I am new in the reactive programming world. I am currently working in a Java reactive application using the Mutiny library.
I need to develop a loop that waits for the previous iteration to finish in order to start the next one. For instance:
List<Uni<T>> uniList = new ArrayList<>();
for (T item : items) { //items is an already fulfilled collection
uniList.add(this.doSomethingAndReturnInUni(item));
}
return Uni.combine().all().unis(uniList).combinedWith(unisToCombine -> {
List<T> list = new ArrayList<>();
unisToCombine.forEach(x ->list.add(x));
return list;
});
The for loop in the example, generates a thread per iteration. I am wondering how to order the i-th call to the method doSomethingAndReturnInUni() waits for the (i-1) call to trigger the event, that is, make the for loop sequentially. It is possible to suscribe those events in such a way?
Could you try something like this?
Builder<Item> items = Uni.join().builder();
for (Item item : items) {
builder.add(this.doSomethingAndReturnInUni(item));
}
return builder.joinAll().andCollectFailures()
.flatMap(itemList -> do whatever you need ...) //itemList type is List<Item>
I don't know why you are using uni, as this should just handle one operation, for loops you should use multi, where you can handle the back pressure, and only get the next event, when one event is finished. Multi can be run sequentially and in parallel.
see https://quarkus.io/blog/mutiny-back-pressure/
I’ve done the same, using Multi’s see the ‘generateData()’ method here:
https://github.com/Serkan80/quarkus-quickstarts/blob/development/redis-streams-quickstart/weather-producer/src/main/java/org/acme/redis/streams/producer/ValuesGenerator.java

Binding.scala: Strategy to avoid too many dom-tree updates

In my project scala-adapters I display log entries that are sent over a websocket.
As I have no control on how many entries are sent, I am looking for a strategy to avoid that the screen freezes.
I created a ScalaFiddle to simulate that: https://scalafiddle.io/sf/kzr28tq
This function with these parameters works perfectly:
setInterval(1000) { // note the absence of () =>
entries.value += (0 to 100).map(_.toString).mkString("")
}
If the interval gets smaller and the String longer - the screen freezes, e.g. with:
setInterval(100) { // note the absence of () =>
entries.value += (0 to 10000).map(_.toString).mkString("")
}
Is there a solution to solve that on the client side - or do I have to solve that on the server side?
You can try:
#dom
def render = {
<div>
{
for (entry <- entries) yield {
entryDiv(entry).bind
}
}
</div>
}
The problem is that you bind entries too early. Binding.scala does its magic by CPS transform, every .bind triggers re-evaluation of all code after, so you should bind a variable as late as possible.
And for Vars, use for comprehension instead of bind directly, to avoid updating the whole list. When you use += to modify the content of Vars, Binding.scala "patches" the list internally, but if you do .bind on the Vars instance directly to get the whole list, the framework cannot do any optimization for you.
Here is the updated ScalaFiddle: https://scalafiddle.io/sf/kzr28tq/3

Array of observables where the output of each is the input of the next

I'm trying to use RxSwift to execute actions on multiple data sources. However, I have no idea how to accomplish the following.
I have an array of observabless where the output of each, should be the input of the next. So, I want to do something like, get the first observable, wait for the result and pass it to the next, all the way to the end of the array and return one final value.
Is that possible? Thanks in advance.
*** Update: Ok, I'll be more specific as requested.
The 'observables' I'm using in the array, are custom. I use a function that returns Observable.create { ... }. Inside the closure, I run an asynchronous operation that transforms the value and then send the result to the observer before completing. That resulting value, must pass to the next observable, and so on to the last observable in the array to get a final value.
The observables may send multiple values, but they must pass from one observable to the next like an assembly line.
It is difficult to know exactly what you are asking for, since Observables do not exactly have inputs but I think this is a common problem.
You may be looking for a combination of the concat or reduce operators, which allow you to accumulate data from the values emitted from an Observable. See ReactiveX's documentation for Mathematical and Aggregate Operators.
Hopefully this can get you started:
// "I have an array of observables..."
let one = Observable.deferred { Observable.just(1) }
let two = Observable.deferred { Observable.just(2) }
let observables = [one, two]
// "the output of each, should be the input of the next"
// this is problematic, because observables do not strictly have inputs.
let resultsFromEach = Observable.concat(observables)
resultsFromEach
.reduce(0) { result, next in
result + 1
}
.debug("result")
.subscribe()

List/Object searching in CoffeeScript

I'm trying to get my head around using CoffeeScript comprehensions as efficiently as possible. I think I have basic mapping down -- turning one list into another -- but searching still seems verbose to me.
Say I have a map of items to shops:
shopMap:
toyStore: ["games", "puzzles"]
bookStore: ["novels", "picture books"]
and, given an item, I want to find out which shop it's in. What's the best way of doing that in CoffeeScript?
Here's how I could do in in JavaScript:
var shop = findShop(item);
function findShop(item) {
for (shop in shopMap)
itemList = shopMap[shop]
for (i = 0, ii = itemList.length; i<ii; i++) {
if (itemList[i] === item) {
return shop;
}
}
}
}
I used a function to allow it to quickly break out of the loops with the return statement, instead of using breaks, but the function is kind of fugly as this is only being used once.
So is there a shorter CS equivalent preferably one that doesn't require creating a new function?
You can try this:
findShop = (item) ->
for shop, items of shopMap
return shop if item in items
If you really want to try with a list comprehension, this is equivalent:
findShop = (item) ->
(shop for shop, items of shopMap when item in items)[0]
But i think the first one reads better (and also doesn't need to generate an intermediate array for the results). This would be a better approach IMO if you wanted to find all shops for a given item:
findShops = (item) ->
shop for shop, items of shopMap when item in items
If this is a common operation, you might be better off creating an intermediate data structure up front and doing the lookup directly.
shopMap =
toyStore: ["games", "puzzles"]
bookStore: ["novels", "picture books"]
categoryMap = {}
for k, v of shopMap
for category in v
categoryMap[category] = k
alert(categoryMap['puzzles'])
Demo
With this implementation you need to loop through the structure only once up front (plus possibly update it if shopMap changes). With yours and epidemian's answer, you have to loop every time you need to do this particular type of lookup. If you do this operation a lot, it could make a difference. On the other hand, if your shopMap is really large (like thousands of entries), then my implementation will take up more memory.
Depending upon how robust you want to make this, you might want to turn it into a Class and have any operations on it occur through the Class' interface. You'd need addCategory and deleteCategory methods as well as a getStoreFromCategory method, which is essentially what we are implementing above. This object-oriented approach would hide the internal data-structure/implementation so you could later alter the implementation to optimize for memory or speed.