java - Opposite of broadcast -
i can create source, has integers {1, 2, 3} , using broadcast create me n sources, , each have {1, 2, 3}.
i want opposite, have n sources , each should provide same integers {1, 2, 3} , using ??? want create single source, have {1, 2, 3}.
i call operation ??? "implode" not have better name.
to answer obvious question comes mind: "why weird thing , not take of sources" have note, n sources expected provide same data, in practice may not respond @ all. if respond different data? error violates our business logic, throwing exception ok.
example: have 2 sources (a , b) of integers, , both have {1, 2, 3}. ask both of them @ same time integer. source b responds faster integer 1, imploded source respond 1 (without waiting answer source a).
now ask both sources next element, , time responds faster 2 (i ignoring it's 1) , returning 2 without waiting b.
now ask both sources next element, , throws connectionlostbecausereasonsexception b responds 3 imploded source returns 3 , ok.
so here advantage speed - imploded source fast fastest sources aggregate plus shields me exceptions n-1 sources.
in end, trying implement function like:
<t> source<t, ?> implode(list<source<t, ?>> sources); the closest got using zip - wait results n sources, , (by using function) return of them. shield me exceptions, makes me fast slowest one, , isn't want.
is there implemented strategy mine "implode"? if yes, it's name? if no, how should implement myself?
here have tried:
class multi { static <t> source<t, ?> merger(list<source<t, ?>> sources) { switch(sources.size()) { case 0: throw new runtimeexception("no sources provided!"); case 1: return sources.get(0); default: return source.zipwithn(multi::zip, sources); } } private static <t> t zip(list<t> list) { return list .stream() .reduce(multi::same) .orelsethrow(runtimeexception::new); } private static <t> t same(t first, t second) { if(objects.equals(first, second)) { return first; } else { throw new runtimeexception(); } } public static void main(string[] args) { source<integer, ?> source1 = source.from(arrays.aslist(1, 2, 3, 4)); source<integer, ?> source2 = source.from(arrays.aslist(1, 2, 3)); source<integer, ?> merger = merger(arrays.aslist(source1, source2)); merger .runforeach(system.out::println, actormaterializer.create(actorsystem.create())) .thenrun(() -> system.out.println("done")); } } this code outputs: 1 2 3 done
and like: 1 2 3 4 done
however, zip method called 3 times, don't chance so. second problem wait sources, instead of returning value fast can. covers case of throwing exception when values different, therefore
source<integer, ?> source1 = source.from(arrays.aslist(1, 2, 4)); source<integer, ?> source2 = source.from(arrays.aslist(1, 2, 3)); outputs: 1 2 exception
as expected.
Comments
Post a Comment