Nino
04/14/2023, 2:20 PMcontext(ViewModel)
fun <T> Flow<T>.stateInViewModel(initialValue: T? = null): StateFlow<T?> = stateIn(
this@stateInViewModel.viewModelScope,
started = SharingStarted.WhileSubscribed(
stopTimeoutMillis = 5_000,
replayExpirationMillis = 0,
),
initialValue = initialValue,
)
But this@stateInViewModel
won't resolve to ViewModel, only to Flow<T>
. I thought I could get the ViewModel instance with Context Receivers, but it doesn't seem like it. Why ?Nino
04/14/2023, 2:22 PMcontext(ViewModel)
fun <T> Flow<T>.stateInViewModel(initialValue: T? = null): StateFlow<T?> {
val viewModel: ViewModel = this@stateInViewModel
return stateIn(
viewModel.viewModelScope,
started = SharingStarted.WhileSubscribed(
stopTimeoutMillis = 5_000,
replayExpirationMillis = 0,
),
initialValue = initialValue,
)
}
produces Type mismatch: inferred type is Flow<T> but ViewModel was expected
ephemient
04/14/2023, 2:23 PMthis@stateInViewModel
to mean something other than the Flow<T>
that is the receiver?ephemient
04/14/2023, 2:24 PMthis@ViewModel
for the contextNino
04/14/2023, 2:25 PMthis@stateInViewModel
cannot represent the context
, then I have no idea of the purpose of context
Nino
04/14/2023, 2:25 PMephemient
04/14/2023, 2:26 PMthis
always means exactly one thing. context
allows name lookup to happen through multiple different scopes.ephemient
04/14/2023, 2:27 PMthis@stateInViewModel
were ViewModel
, how would you get a reference to the Flow<T>
?Nino
04/14/2023, 2:27 PMcontext
Nino
04/14/2023, 2:27 PMTgo1014
04/14/2023, 2:28 PMephemient
04/14/2023, 2:28 PMclass Foo {
fun Bar.f() {
flow {
this // flow
this@f // Bar
this@Foo // Foo
ephemient
04/14/2023, 2:28 PMcontext(Foo)
⇒ this@Foo
Nino
04/14/2023, 2:28 PMNino
04/14/2023, 2:28 PMNino
04/14/2023, 2:29 PMcontext(ViewModel)
fun <T> Flow<T>.stateInViewModel(initialValue: T? = null): StateFlow<T?> = stateIn(
this@ViewModel.viewModelScope,
started = SharingStarted.WhileSubscribed(
stopTimeoutMillis = 5_000,
replayExpirationMillis = 0,
),
initialValue = initialValue,
)
Worksephemient
04/14/2023, 2:29 PMephemient
04/14/2023, 2:30 PMNino
04/14/2023, 2:30 PM