nayanjyoti
08/09/2018, 7:44 AMprivate const val corePoolSize = 8
private val executor = Executors.newScheduledThreadPool(corePoolSize)
private val dispatcher = executor.asCoroutineDispatcher()
fun <T, R> Deferred<T>.map(block: (T) -> R): Deferred<R> {
return async(dispatcher) {
val target = this@map.await()
block(target)
}
}
This is one of the extension method I have added to help me with the already used function composition.
Usage is like this:
// since we are calling in java codebase, we need to pass the deferred instance as the receiver
class TypeA {
String xyz;
String abc;
// getter setters are here
}
Deferred<TypeA> a = thirdPartyService.foo()
return map(map(a, (a) -> {
a.setXyz("xyz");
return a; // yes I understand that this is more of a consume like function than a map
}), (a) -> {
// some more logic on a instance
if (a.getXyz().equals("abc")) {
// do something
}
});
In my understanding if I chain multiple map invocations, it should first resolve the inner map invocation in this case, which means the xyz field should not be null, however, I receive NPE in the if (a.getXyz().equals("abc")) line. I also added debug statements on the setXyz line and in the a.getXyz().equals line. I noticed the second lambda is invoked first then the first lambda.
Can anyone help me out with understanding this scenario? In my understanding it should have invoked the first lambda then the second one.