Home > Software design >  How can we placing a logger statement inside orElse() block
How can we placing a logger statement inside orElse() block

Time:03-23

snippet: logger is required for the else condition...

fun performEvent(type: String, event: MyEvent, relId: UUID): Mono<MyBaseEvent>{
    return processorById.getOrDefault(type,null)!!.handleTask(event,relId)
       .map{
          kTamplate.send(getResultMessage(it))
          Mono.just(it)
        }.orElse(Mono.emplt())  // a logger is required for orElse case
    
}

CodePudding user response:

Since map {...} always returns a List, you could use .ifEmpty().

This would be the case for a non-empty list:

val list = listOf("a", "b")

val result = list
  .map { it }
  .ifEmpty { 
    println("empty")   // will be skipped
    emptyList()        // will be skipped
  }

println(result)   // Output: [a, b]

And if the list is empty the same code would produce this:

val list = emptyList<String>()

val result = list
  .map { it }
  .ifEmpty { 
    println("empty")   // Output: empty
    emptyList() 
  }

println(result)   // Output: []

CodePudding user response:

You can use Mono.defer to log and create the empty Mono:

...orElse(Mono.defer{ 
   /* log here */
   Mono.empty()
})

Or, if it is okay that the logging is evaluated at the time of the orElse statement, you could just use also:

...orElse(Mono.empty().also { /* log here */ })

Moreover, if it is Optional.orElse you are using, you could just switch to orElseGet:

...orElseGet { 
   /* log here */
   Mono.empty()
}
  • Related