https://kotlinlang.org logo
#flow
Title
# flow
l

Logan Knight

01/29/2021, 6:40 PM
Can some one confirm my understanding about emitting from a callback? See thread.
The only two ways to accomplish this:
Copy code
val someExternalApi = SomeExternalApi()

fun flowExample(): Flow<Int> = flow {

    someExternalApi.addListener {
        scope.launch {
            emit(it)
        }
    }
}

flowExample().collect { println(it) }
are:
Copy code
val _events = MutableSharedFlow<Int>()
val events = _events.asSharedFlow()

val someExternalApi = SomeExternalApi()

someExternalApi.addListener {
    scope.launch {
        _events.emit(it)
    }
}

events.collect { println(it) }
Or
Copy code
val someExternalApi = SomeExternalApi()

fun flowExample(): Flow<Int> = callbackFlow {
    val callback: (int: Int) -> Unit = {
        offer(it)
    }

    someExternalApi.addListener(callback)
}

flowExample().collect { println(it) }
I would rather not use the callback flow since it's experimental and using the
sharedFlow
seems incorrect since it's intended purpose is
for broadcasting events that happen inside an application to subscribers that can come and go
3 Views