Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get flow output from non flow fuction

I want flow output (return type Flow<T>) from a non-flow function (return typeT).

fun getTotalFiles(): Int 
// Say, This is a library function it'll return the number of files (Int) in that folder at that specific moment.

//And,
fun getAllFiles(): List<File> 
// Say, This is a library function it'll return all the files (List<File>) in that folder.

The files in that folder can and will change in the future.

Now, I want to constantly observe the output, so how do I implement it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

fun getFlowOfTotalFiles(): Flow<Int> =
// A wrapper function that converts the library function return type to an observable flow, Flow<Int>

//And,
fun getFlowOfAllFiles(): Flow<List<File>> =
// A wrapper function that converts the library function return type to an observable flow, Flow<List<File>>

>Solution :

I believe you need an infinite loop inside a flow builder, something like the following:

fun getFlowOfTotalFiles(): Flow<Int> = flow {
    while (true) {
        emit(getTotalFiles())
        // delays for 5 sec before next request and 
        // terminates the infinite cycle when a coroutine, 
        // that collects this Flow, is canceled
        delay(5000) 
    }
}

fun getAllFilesFlow(): Flow<List<File>> = flow {
    while (true) {
        emit(getAllFiles())
        delay(5000)
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading