How to convert a akka.stream.javadsl.Source to java.util.concurrent.Flow.Publisher - akka-stream

I'm experimenting with the Test Compatability Kit (tck) for reactive Streams, and having tested a few Publishers myself, I wanted to test an akka Source. But in order to do so I need to convert a Source (or Source + Processor(s)) to a java.util.concurrent.Flow.Publisher.
#Override
public Flow.Publisher<Integer> createFlowPublisher(long elements) {
return new FlowPublisher((int) elements); // <-- how to test an akka.Source?
}
class FlowPublisher implements java.util.concurrent.Flow.Publisher {
...
And I can't find anywhere how to do this.
Is there somehwere some documentation on this, or does someone know the answer by heart?

you can convert akka-streams Source to org.reactivestreams.Publisher (which is the same as java.util.concurrent.Flow according to reactive-streams):
implicit val sys: ActorSystem = ActorSystem()
implicit val mat: ActorMaterializer = ActorMaterializer()
val source = Source.single(1) // some random source
val publisher: Publisher[Int] = source.runWith(Sink.asPublisher(false))
you can find details in the official akka-streams docs - Integrating with Reactive Streams
the thing to note is that akka-streams has documention and some kits for testing its' component - Testing streams. i would say that it's better to test akka-streams components with akka-streams testing kit, because you don't need to make additional conversions to org.reactivestreams.* entities and the testing code will be much cleaner, simpler and reliable

Related

How to update UI with a viewModel for byte arrays and lists in Kotlin/Jetpack Compose?

So the problem I am facing is that when the viewModel data updates it doesn't seems to update the state of my bytearrays: ByteArray by (mutableStateOf) and mutableListOf()
When I change pages/come back to the page it does update them again. How can get the view to update for things like lists and bytearrays
Is mutableStateOf the wrong way to update bytearrays and lists? I couldn't really find anything useful.
Example of byte array that doesn't work (using this code with a Float by mutableStateOf works!).
How I retrieve the data in the #Composable:
val Data = BluetoothMonitoring.shared.Data /*from a viewModel class, doesn't update when Data / bytearray /list changes, only when switching pages in app.*/
Class:
class BluetoothMonitoring : ViewModel(){
companion object {
val shared = BluetoothMonitoring()
}
var Data : ByteArray by mutableStateOf( ByteArray(11) { 0x00 })
}
Any help is appreciated and thanks in advance!
You seem to come from IOS/Swift where using Shared objects is a common pattern
In Android, you're not supposed to create a viewmodel instance by hand, you are supposed to use ViewModelFactory, or compose viewModel() function. The ViewModel object basically preserves some data for you across activity recompositions, i.e. when activity is paused, resumed etc
The general good way of structuring your app is using UDF (Unidirectional Data Flow) where, data flows upwards towards the view/composable and events flow downwards towards the viewmodel, data layer etc. We use something called as Flow which is a reactive data stream, which updates the listener whenever some value changes
Keeping in mind these two points, I've created a very brief way of how you could restructure your code, so that it almost always works. Please adapt accordingly to your logic
class MyViewModel: ViewModel(){
// Declare a flow in the viewModel
var myData = MutableStateFlow(0)
fun modifyMyData(newData: Int){
myData = newData
}
}
And in your composable view layer
#Composable
fun YourComposable(){
val myViewModel = viewModel()
val myUiState by myViewModel.myData.collectAsState()
// Now use your value, and change it, it will be changed accordingly and updated everywhere
}
I also recommend reading this codelab
How I handle byte arrays over Bluetooth with kotlin and Android.
I'm talking sic (communication) to arduino over bluetooth in the app I'm making. Kotlin likes Byte and Arduino likes UBYTE so I do all of those translations in the app because Kotlin threads are inline code easy and the phone has more power for such things.
Add toByte() to everthing that is outbound. <- (actual solution)
outS[8] = Color.alpha(word.color).toByte()
outS[9] = Color.red(word.color).toByte()
outS[10] = Color.green(word.color).toByte()
outS[11] = Color.blue(word.color).toByte()
outS[12] = 0.toByte()
outS[13] = 232.toByte()
outS[14] = 34.toByte()
outS[15] = 182.toByte()
//outS[16] = newline working without a newLine!
// outS[16] = newline
val os = getMyOutputStream()
if (os != null) {
os.write(outS)
}
For inbound data...I have to change everything to UByte. <- (actual solution)
val w: Word = wordViewModel.getWord(i)
if (w._id != 0) {
w.rechecked = (byteArray[7].toInt() != 0)
w.recolor = Color.argb(
byteArray[8].toUByte().toInt(),
byteArray[9].toUByte().toInt(),
byteArray[10].toUByte().toInt(),
byteArray[11].toUByte().toInt()
)
//finally update the word
wordViewModel.update(w)
}
My Youtube channel is about model trains not coding there some android and electronics in there. And a video of bluetooth arduino android is coming soon like tonight or tomorrow soon. I've been working on the app for just over a month using it to learn Kotlin. The project is actually working but I have to do the bluetooth connection manually the app actually controls individual neopixels for my model train layout.

Akka doc is unclear about how to get an ExtendedActorSystem to deserialize ActorRef

I'm trying to serialize/deserialize ActorRef through protobuf. According to the Akka doc, the only way to do it is to convert the ActorRef into a String, and convert it back in the remote actor system.
The doc mentions using an ExtendedActorSystem to do the deserialization (see here). However, it is unclear how to get the ExtendedActorSystem:
// Serialize
// (beneath toBinary)
val identifier: String = Serialization.serializedActorPath(theActorRef)
// Then just serialize the identifier however you like
// Deserialize
// (beneath fromBinary)
// ==== Where is this extendedSystem from? ====
val deserializedActorRef = extendedSystem.provider.resolveActorRef(identifier)
// Then just use the ActorRef
Edit
I found this question here: Akka (JVM): Serialize an actorref with protobuf within another message, which mentions casting an ActorSystem to ExtendedActorSystem. Is this the right approach? Will it always work?
dear #stackoverflower,
whenever you use ActorSystem(...) it build an instance of ActorSystemImpl.
The type-tree looks like:
ActorSystemImpl extends ExtendedActorSystem
and
ExtendedActorSystem implements ActorSystem
you can use statements like
val system: ExtendedActorSystem = ActorSystem(...).asInstanceOf[ExtendedActorSystem]
to access the correct type autocomplete. ActorSystemImpl is unfortunately scoped to [akka].

How to use Collections.binarySearch() in a CodenameOne project

I am used to being able to perform a binary search of a sorted list of, say, Strings or Integers, with code along the lines of:
Vector<String> vstr = new Vector<String>();
// etc...
int index = Collections.binarySearch (vstr, "abcd");
I'm not clear on how codenameone handles standard java methods and classes, but it looks like this could be fixed easily if classes like Integer and String (or the codenameone versions of these) implemented the Comparable interface.
Edit: I now see that code along the lines of the following will do the job.
int index = Collections.binarySearch(vstr, "abcd", new Comparator<String>() {
#Override
public int compare(String object1, String object2) {
return object1.compareTo(object2);
}
});
Adding the Comparable interface (to the various primitive "wrappers") would also would also make it easier to use Collections.sort (another very useful method :-))
You can also sort with a comparator but I agree, this is one of the important enhancements we need to provide in the native VM's on the various platforms personally this is my biggest peeve in our current VM.
Can you file an RFE on that and mention it as a comment in the Number issue?
If we are doing that change might as well do both.

How can I use solr handlers internally?

So assume I want to implement custom morelikethis(or autosuggest) experience by merging output of two different morelikethis handler configurations.
Pseudo code could look like
class MyMoreLikeThis extends SearchHanlder {
def process(reqBuilder) {
val mlt1 = reBuilder.getComponent("/mlt1");
val mlt2 = reBuilder.getComponent("/mlt2");
val rb1 = reqBuilder.copy()
val rb2 = reqBuilder.copy()
reqBuilder.results = mlt1.process(rb1).getResults ++ mlt1.process(rb2).getResults
}
}
Or probably I can use solrj API to access solr from inside.
How can I do this? Is there better way to do this?
You can refer to the below blog posts that has detailed explanation on how to achieve merging results from different queries similar to the problem that you are talking about,
Custom Search Handler
Idea#1
Custom Search Handler
Idea#2
The blog is authored by a former colleague of mine who has number of years expertise with Search & Information Retrieval.

Saving type information of datastructures

I am building a framework for my day-to-day tasks. I am programming in scala using a lot of type parameter.
Now my goal is to save datastructures to files (e.g. xml files). But I realized that it is not possible using xml files. As I am new to this kind of problem I am asking:
Is there a way to store the types of my datastructures in a file??? Is there a way in scala???
Okay guys. You did a great job basicly by naming the thing I searched for.
Its serialization.
With this in mind I searched the web and was completly astonished by this feature of java.
Now I do something like:
object Serialize {
def write[A](o: A): Array[Byte] = {
val ba = new java.io.ByteArrayOutputStream(512)
val out = new java.io.ObjectOutputStream(ba)
out.writeObject(o)
out.close()
ba.toByteArray()
}
def read[A](buffer: Array[Byte]): A = {
val in = new java.io.ObjectInputStream(new java.io.ByteArrayInputStream(buffer))
in.readObject().asInstanceOf[A]
}
}
The resulting Byte-Arrays can be written to a file and everthing works well.
And I am totaly fine that this solution is not human readable. If my mind changes someday. There are JSON-parser allover the web.

Resources