Home > Mobile >  How can we place a logger statement inside an orElse() block?
How can we place a logger statement inside an orElse() block?

Time:03-24

I have the following function that returns a Mono.

    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.empty())  // a logger is required for orElse case
        
    }

Is there a way to add a logging statement inside the orElse at the end?

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()
}

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: []
  • Related