Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

200
Visualizações
Pass a lazy parameter to function

I have a function that needs to call another function to do work. I want to delay the second function call until needed. The reason is that sometimes the second function call is not needed.

The code looks like this:

suspend fun doWork(list: List<A>) {
    if(list.isEmpty()) return
    
    secondFunction()
}

However, secondFunction() has to be determined by the caller of the function. Is there a way to do this maybe by using lambda?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You could try using a lambda to delay the execution of your second function until you need the value.

suspend fun doWork(
   list: List<A>,
   lambdaFunction: suspend () -> Unit
) {
    ...
    lambdaFunction()
}

Or you can have it return a value.

suspend fun doWork(
   list: List<A>,
   lambdaFunction: suspend () -> String
) {
    ...
    val result = lambdaFunction()
}

You would call it like this:

doWork(
   list = list, 
   lambdaFunction = { secondFunction() }
)

I also made it suspend because I saw you using suspend. You don't have to use suspend.

over 4 years ago · Santiago Trujillo Relatório

0

What it looks like you want can be solved via the Observer Pattern

Ill show you in rxKotlin

val subject = PublishSubject.create<Observable<List<A>>>()

subject.subscribeBy(
    onNext = { doWork(it) },
    onError =  { it.printStackTrace() },
    onComplete = { println("Done!") }
)

And when the list is ready.

subject.oNext(list)

The doWork function will be called and you don't need to block the use of secondFunction as list will contain the values.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda