Skip to content

How to use Flows in an imperative mode? #4113

@mahozad

Description

@mahozad

Use case
Suspending functions and the code in a coroutine can be used like normal imperative code.

But Flows can be used only in a reactive way (on X do Y).

I'm just curious, is there any way to use Flows like "regular" code?

Example of current declarative way:

myComponent
    .getSomeThings()
    .onStart { /* START */ }
    .onEmpty { /* EMPTY */ }
    .onEach { /* EACH */ }
    .onCompletion { /* COMPLETE */ }
    .catch { /* EXCEPTION */ }
    .launchIn(myCoroutineScope)

to be written like this:

myCoroutineScope.launch {
    val flow = myComponent.getSomeThings()
    /* START */
    if (flow.isEmpty()) /* EMPTY */
    while (flow.isNotComplete()) {
        val item = flow
            .runCatching { getNext() }
            .getOrElse { /* EXCEPTION */ }
        /* EACH */
    }
    /* COMPLETE */
}

The Shape of the API
Something like the above example. I'm not sure if all the functionalities of various Flow operators can be achieved in imperative code.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions