How to fold results from a few async calls - kotlin

I want to get the results of my asynchronous function and use them in the fold function. Here's my function that didn't work:
private fun sendOrderStatus(list: List<OrderStatusEntity>) : Single<Boolean> {
return Single.just(
list.fold(true) { initial, item ->
if (!item.isTerminal()) {
val info = OrderStateParameters(
lon = item.orderStatusLon!!,
lat = item.orderStatusLat!!,
datetime = item.orderStatusDate!!
)
val state = OrderState(item.orderId, item.toSend(), info)
return tasksUseCase.sendOrderStatusForWorker(state)
.doOnSuccess { markSent(item) } // side calling
.flatMap {
return#flatMap initial && it.isSuccess // that result should be used in *fold*-function
}
} else // stub result
true
}
)
}
So, I intend to return a Single that will contain the aggregated result of all tasksUseCase.sendOrderStatusForWorker(state) calls.
Thank for any helps!

Related

How to return error as value from failable function?

The current release of Zig is 0.10.1 at the time of asking this question. The language is not yet stable and is subject to change.
How can I return an error as value from a failable function? I have tried the following, but it returns it as an error instead of returning it as a value:
fn foo_1() !anyerror {
// Returns outer error.
return error.Oops;
}
fn foo_2() !anyerror {
// Returns outer error.
var error_ = error.Oops;
return error_;
}
I would like to return it as value such that the following code to print out the error instead of propagating it when try is evaluated:
fn bar() !void {
var error_ = try foo();
std.debug.print("got error: {any}\n", .{ error_ });
}
I am asking this because I am trying to learn the language. I don't have a concrete use-case for this. However, I am curious if this is possible to do.
A similar related situation is to return an optional value which itself is optional (for example when forwarding the result of a function which returns an optional), but I was already able to find a solution for that:
fn baz_1() ??i32 {
// The outer optional is null.
return null;
}
fn baz_2() ??i32 {
// The inner optional is null.
var value: ?i32 = null;
return value;
}
Is something like that possible for errors as well?
No, it's not allowed in Zig. If you try you'll get an error like "error union with payload of error set type 'error{Def}' not allowed".
However, you can wrap the error in a struct:
const std = #import("std");
const ErrorError = error{
Abc,
};
const ErrorValue = error{
Def,
};
const WrappedError = struct {
err: ErrorValue,
};
fn foo() ErrorError!WrappedError {
return .{
.err = ErrorValue.Def,
};
}
test "returns error value" {
var bar = try foo();
std.debug.assert(bar.err == ErrorValue.Def);
}
error values can be declared with error{...} syntax. see https://ziglang.org/documentation/master/#Errors
pub const Error = error{Bar};
fn foo() error{Bar} {
return error.Bar;
}
// or anyerror
fn foo() anyerror {
return error.Bar;
}

If else on Mono if empty or has value

This is the sample code
repo1.findById( id )
.map( p -> {
if( p == null ){
return repo2.findById( id ).flatMap( g -> {
g.setValue("some value");
return g;
});
}
else{
return repo3.findById( id ).flatMap( h -> {
h.setValue("some value");
return h;
});
}
});
Any better way to do this ?. If else inside flat map does not look neat to me.
The idiomatic approach would be to use the switchIfEmpty() operator.
You would only proceed to use the call to repo3 if repo1 actually returns a result.
If not data matches repo1.findById(id), then this call would return an empty result, not null.
To cover this case, use switchIfEmpty().
public Mono<Data> load(String id){
return repo1.findById(id)
.flatMap(p -> {
return repo3.findById(id)
.flatMap(h -> {
h.setValue("some value");
return h;
});
})
.switchIfEmpty(repo2.findById(id)
.flatMap(g -> {
g.setValue("some value");
return g;
}));
}

How to get object of Maximum value from LiveData?

I have liveData of market data. I want one market data object which have highest 'volume'. Here, volume is string value("277927.5793846733451135"), it could be null also.
I am using below code to achieve this. but, its not working.
viewModel.marketlist.observe(this as LifecycleOwner, { marketdata ->
val marketData = marketdata.getOrNull()
if(marketData !=null) {
val mData: MarketData? = marketData.marketData?.maxByOrNull { checkNotNull(it.volume) }
if (mData != null) {
binding.textViewPrice.text = mData.price
}
}
else {
//TODO
}
})
Any help would be appreciated!
You should be able to do something like this:
viewModel.marketList.observe(viewLifecycleOwner) { marketData ->
val maxData = marketData.getOrNull()?.marketData?.let { dataValues ->
dataValues.maxByOrNull { it.volume?.toDoubleOrNull() ?: -1.0 }
}
if (maxData != null) {
binding.textViewPrice.text = maxData.price
}
}
I cleaned up the observe call a bit, then I'm checking if marketData.getOrNull().marketData is null right away with my let { ... } block.
If you do have marketData (the inner one), it'll then safely call maxByOrNull { it.volume }.

Pass by value. Array

I have two arrays. But when I change second - first change too.
I tried
.clone()
.copyOf()
but it didn't work for me.
object MatrixObject {
var table: Array<Array<Int>>? = null
fun randOf(n: Int) {
table= Array(n, { Array(n, { Random().nextInt(100 - 0) + 0 }) })
}
var tableF: Array<Array<Int>>? = null
get() {
if (field==null)
factorization()
return field
}
fun factorization() {
tableF = table!!
... //here I change elements of tableF
}
}
I tried
for(row in 0 until table!!.size)
tableF!![row] = Arrays.copyOf(table!![row], table!![row].size)
and
for(row in 0 until table!!.size)
tableF!![row] = table!![row].clone() // and copyOf()
but it still doesn't work.
I found the solution.I initialized the array.
tableF= Array(table!!.size, { Array(table!!.size, {0}) })
for(row in 0 until table!!.size)
tableF!![row] = table!![row].clone()

Return Option inside Loop

The program aims to use a loop to check if the index of a iterator variable meets certain criteria (i.g., index == 3). If find the desired index, return Some(123), else return None.
fn main() {
fn foo() -> Option<i32> {
let mut x = 5;
let mut done = false;
while !done {
x += x - 3;
if x % 5 == 0 {
done = true;
}
for (index, value) in (5..10).enumerate() {
println!("index = {} and value = {}", index, value);
if index == 3 {
return Some(123);
}
}
return None; //capture all other other possibility. So the while loop would surely return either a Some or a None
}
}
}
The compiler gives this error:
error[E0308]: mismatched types
--> <anon>:7:9
|
7 | while !done {
| ^ expected enum `std::option::Option`, found ()
|
= note: expected type `std::option::Option<i32>`
= note: found type `()`
I think the error source might be that a while loop evaluates to a (), thus it would return a () instead of Some(123). I don't know how to return a valid Some type inside a loop.
The value of any while true { ... } expression is always (). So the compiler expects your foo to return an Option<i32> but finds the last value in your foo body is ().
To fix this, you can add a return None outside the original while loop. You can also use the loop construct like this:
fn main() {
// run the code
foo();
fn foo() -> Option<i32> {
let mut x = 5;
loop {
x += x - 3;
for (index, value) in (5..10).enumerate() {
println!("index = {} and value = {}", index, value);
if index == 3 {
return Some(123);
}
}
if x % 5 == 0 {
return None;
}
}
}
}
The behaviour of while true { ... } statements is maybe a bit quirky and there have been a few requests to change it.