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

Lilly

03/08/2023, 11:52 PM
Is there some mechanism to defer a collection via
collectAsState
, e.g. when a button is pressed. In a MVC architecture I'm currently doing this:
Copy code
class Presenter {
 val uiState: UiState by lazy { UiState() }

 fun startCollection(uiScope: CoroutineScope) {
   useCase.myFlow().onEach { counter -> uiState.counter = counter }.launchIn(scope)
 }
}

class UiState {
 var counter by mutableStateOf(0)
}

@Composable
fun MyScreen(presenter: Presenter) {
 val scope = rememberCoroutineScope()
 when(action) {
   someEvent -> presenter.startCollection(scope)
 }
}
Just curious if there are other more concise options?
s

s3rius

03/11/2023, 8:54 PM
Copy code
var collectionEnabled = false

fun startCollection() { collectionEnabled = true }

init {
    useCase.myFlow().filter(collectionEnabled).onEach { ... }.launchIn(..)
}
This comes to mind. Ofc it keeps the flow active from the very start, which may or may not be bad.
l

Lilly

03/11/2023, 10:52 PM
Thanks @s3rius I came to the conclusion that my solution is as good as is. I think there is seldom a good reason to collect a flow in screen...better done in presenter/vm. The only good reason to do so is when u want to make presenter unaware of jetpack compose by not using
mutableStateOf
5 Views