https://kotlinlang.org logo
#coroutines
Title
# coroutines
d

David Glasser

02/29/2020, 2:43 AM
I'm making a flow that produces a list of files from Google Cloud Storage through running paginated executions. The actual RPCs should be in Dispatchers.IO (I think!). I'm not sure if I'm supposed to use withContext for this or flowOn. What I have is:
Copy code
fun listFiles(bucket: String, prefix: String): Flow<Blob> = flow {
		var page = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
			gcs.list(bucket, BlobListOption.prefix(prefix))
		}
		while (true) {
			emit(page)
			if (!page.hasNextPage()) {
				break
			}
			page = withContext(<http://Dispatchers.IO|Dispatchers.IO>) { page.nextPage }
		}
	}.flatMapConcat { page ->
		page.values.asFlow()
	}
but I don't know if that is right
l

louiscad

02/29/2020, 6:27 AM
Use
flowOn
d

David Glasser

02/29/2020, 7:15 AM
like this?
Copy code
flow {
		var page = gcs.list(bucket, BlobListOption.prefix(prefix))
		while (true) {
			emit(page)
			if (!page.hasNextPage()) {
				break
			}
			page = page.nextPage
		}
	}
		.flowOn(<http://Dispatchers.IO|Dispatchers.IO>)
		.flatMapConcat { page -> page.values.asFlow() }
l

louiscad

02/29/2020, 8:20 AM
Indent is not standard (should be 4 spaces). Looks correct to me, but I recommend you to read the docs of
flowOn
(and
Flow
) in general to understand what you do and get confidence.
6 Views