Home > Mobile >  Pass a lazy parameter to function
Pass a lazy parameter to function

Time:11-23

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?

CodePudding user response:

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.

CodePudding user response:

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) },
    one rror =  { 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.

  • Related