How to Convert RxJava (Single firstOrError() ) to Kotlin Flow? - kotlin

I have Observable on which i apply firstOrError() operator which return a Single<T>
Same i want to convert into Kotlin Flow. I want there must be some mechanism which return a flow with 1st item or error.
Do you have any idea on this how i can achieve that?

To convert Observable into Flow, you can use asFlow from kotlinx.coroutineslibrary.
Note that there is no way to convert Single into Flow because those are two incompatible types (single-value vs stream). But you can convert your Observable into Flow with asFlow first and then instead of firstOrError() use first().

Related

Convert java Optional to Kotlin Arrow Option

What would be the best way to convert Java Optional to Arrows Option? I was expected to have something out-of-box, but it's not there. Something like:
fun <T> Optional<T>.toOption(): Option<T> = if (this.isPresent) Some(this.get()) else none()
There is no such function at the moment, but such a contribution would be welcomed!
Arrow however does not recommend using Option unless absolutely necessary. The only use-case being nested nulls, which is the limitation for ReactiveX implementation of RxJava & Project Reactor. Both libraries don't allow null being used for their generic value A in Flowable, Flux, Mono, etc.
Analogue, you cannot use null as an empty signal for generic code in Kotlin. Unless A is constraint to be non-null by using A : Any.
Only in both cases should you use Arrow's Option, otherwise using Kotlin's nullable type is recommended by the Arrow maintainers.

Determining when a Flow returns no data

The Kotlin flow states the following:
A suspending function asynchronously returns a single value, but how
can we return multiple asynchronously computed values? This is where
Kotlin Flows come in.
However, if the source of my flow is such that when it completes but returns no data, is there a way to determine that from the flow? For example, if the source of the flow calls a backend API but the API returns no data, is there a way to determine when the flow completes and has no data?
There is an onEmpty method that will invoke an action if the flow completes without emitting any items.
It can also be used to emit a special value to the flow to indicate that it was empty. For example, if you have a flow of events you can emit an EmptyDataEvent.
Or you can just do whatever it is that you want to do inside this onEmpty lambda.
Highly related is also the onCompletion method
If the API returns a Flow, it is usually expected to return 0 or more elements. That flow will typically be collected by some piece of code in order to process the values. The collect() call is a suspending function, and will return when the flow completes:
val flow = yourApiCallReturningFlow()
flow.collect { element ->
// process element here
}
// if we're here, the flow has completed
Any other terminal operator like first(), toList(), etc. will handle the flow's completion in some way (and may even cancel the flow early).
I'm not sure about what you're looking for here, but for example there is a terminal operator count:
val flow = yourApiCallReturningFlow()
val hasAnyElement = flow.count() == 0
There is also onEmpty that allows to emit some specific values instead of the empty flow.
I guess it depends on what you want to do when there are items in the flow.
You can just do toList() on the flow and check if it's empty

what are the various ways to fetch the properties from payload?

What is the difference between reading the properties from payload. for example there is a property in the payload which is named as con_id. when i read this property like this #[payload.con_id] then it is coming as null. where as #[payload.'con_id'] is returning the value.
few other notations which i know of is #[payload['con_id']] or #[json:con_id]
which one should be used at which scenario? if there are any special cases to use any specific notation then please let me know the scenario also.
Also, what is the common notation that has to be used from a mule soft platform supported point of view.
In Mule 3 any of those syntax are valid. Except the json: evaluator is for querying json documents where as the others are for querying maps/objects. Also the json: evaluator is deprecated in Mule 3 in favor of transforming to a map and using the MEL expressions below.
payload.property
payload.'property'
payload['property']
The reason the first fails in your case, is beacaue of the special character '_'. The underscore forces the field name to be wrapped in quotes.
Typically the . notation is preferred over the [''] as its shorter for accessing map fields. And then simply wrap property names in '' for any fields with special chars.
Note in Mule 4, you don't need to transform to a map/object first. Dataweave expression replace MEL as the expression language and allow you to directly query json or any type of payload without transforming to a map first.

How to pass array of struct(User defined data type) as an input to call procedure in mule

In my project we have a requirement where we have to insert an array of struct as an input parameter.How i can achieve that.
I don't want to use the approach suggested here
https://dzone.com/articles/passing-java-arrays-in-oracle-stored-procedure-fro
I want to use the inbuilt objects given in mule.
we have to insert an array of struct as an input parameter
Where you want to insert this array ?
array of struct
can we consider the User defined data type as POJOs ( just java object?) ?
I want to use the inbuilt objects given in mule.
As I can see in the link, the example use Java + Mule component. Should I guess that you want to avoid Java code?
Please, elaborate your use case... hard to replicate

How can I return JSONP in RestXQ (using eXist-db)?

I cannot figure out how to return JSONP in RestXQ. After adding
let $x := util:declare-option("exist:serialize", fn:concat("method=json jsonp=",request:get-parameter("callback", "callback")))
to the function, I get the error message:
err:XPTY0004:It is a type error if, during the static analysis phase, an expression is found to have a static type that is not appropriate for the context in which the expression occurs, or during the dynamic evaluation phase, the dynamic type of a value does not match a required type as specified by the matching rules in 2.5.4 SequenceType Matching.
The beginning of the GET function is:
declare
%rest:GET
%rest:path("/demo/contacts/submit")
%rest:query-param("email", "{$email}", '')
%rest:query-param("nomail", "{$nomail}", 0)
%rest:produces("application/javascript")
%output:media-type("application/javascript")
%output:method("json")
function contacts:submit($email as xs:string*, $nomail as xs:integer*)
{
try
{
let $x := util:declare-option("exist:serialize", fn:concat("method=json jsonp=",request:get-parameter("callback", "callback")))
As discussed on the eXist-open mailing list (I'd suggest joining!), the request module's get-parameter() function is not available inside a RestXQ function. Instead, you can get your callback parameter via the %rest:query-param annotation. Add %rest:query-param("callback", "{$callback}", '') to your contacts:submit() function, and I think you'll be a step closer.
#joewiz is correct. Your initial problem is related to the use of eXist request module from RESTXQ, which is unsupported.
Also, RESTXQ does not currently support JSONP serialization. If you want to use JSONP serialization, your best bet at the moment is to manage the serialization to JSON yourself, perhaps using the xqjson library or similar and then wrapping the result in a JSON function using concat or similar.