Is there some mechanism to defer a collection via ...
# compose
l
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
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
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