hey everyone. I have a question about lambdas and ...
# coroutines
o
hey everyone. I have a question about lambdas and suspend functions. This is the code I have:
Copy code
private suspend fun doWork(
        templateId: FormTemplateId?,
        form: Form?,
        workflow: DraftWorkflow
    ): DraftWorkflow {
        return Pair(templateId, form).fold(
            { formTemplateId, formUpdate ->
                updateUseCase.update(
                    formTemplateId,
                    formUpdate
                )
                workflow.setUrl()
            },
            { formTemplateId ->
                runBlocking {
                    deleteUseCase.delete(formTemplateId)
                }
                workflow
            },
            { formCreate ->
                val newFormId = runBlocking {
                    createUseCase.create(
                        formCreate
                    )
                }
                workflow
                    .setId(newFormId)
            },
            {
                workflow
            }
        )
     }
as you can see
doWork()
is suspend function, but in lambda this suspend doesn’t work properly anymore.
updateUseCase.update()
in this case is a suspend function as well, but compiler gives me an error: Suspension functions can be called only within coroutine body, So I have to wrap all calls to
runBlocking
again to get the expected result. any idea how that can be done without runBlocking? Thanks in advance 🙏
g
I guess the problem is that the functions/lambdas given to
fold
are not suspending. You can probably remove the
fold
function and write simple if/else statements instead, assuming that the behavior of
fold
is easy to inline.
👍 1
o
yeah, that makes sense, but I though I could do some trick with
fold
and make it work 🙂
d
If
fold
can be made an
inline
function, this will also work.
🧠 1