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

dan.the.man

05/13/2021, 5:36 PM
Hi guys, I have a weird one
Copy code
fun <T> LifecycleOwner.stateFlow(stateFlow: StateFlow<T>, funCollect: (T) -> Unit) {
        lifecycleScope.launchWhenStarted {
            stateFlow.collect() {
                funCollect(it)
            }
        }
    }
Is how I subscribe to a Stateflow. I then subscribe to that in my fragment. However, very infrequently, my Stateflow doesn't emit.
Copy code
Timber.d(//This log is hit)
            model.data.emit(result)
The log above is hit, in theory I would think it should have emit, but for some reason, my subscription is never hit in my fragment. The correct object is being pushed to/observed, not sure what's happening, any thoughts?
u

ursus

05/13/2021, 6:36 PM
whats that lambda after collect? doesnt seem right
d

dan.the.man

05/13/2021, 6:37 PM
It's just a log statement atm
u

ursus

05/13/2021, 7:16 PM
does that code compile?
d

dan.the.man

05/13/2021, 7:16 PM
Yes
u

ursus

05/13/2021, 7:29 PM
oh yea the () is optional lol, nevermind ..
I'd venture the lifecyclescope can be busted, or, since emit is suspending its scope can ran out
and also, since its a mutable flow, it only passes through distinct values (it does a == check inside)
d

dan.the.man

05/13/2021, 7:30 PM
Yup. The values are different that are being passed, the lifecyclescope being dead would explain it, but there's no reason it should be
u

ursus

05/13/2021, 7:32 PM
try GlobalScope just to prove
d

dan.the.man

05/13/2021, 9:31 PM
I did a CoroutineScope(DIspatchers.Main().launch and same issue, still sometimes not receiving updates
u

ursus

05/13/2021, 10:02 PM
did you keep it as a field? if not it might get garbage collected
d

dan.the.man

05/13/2021, 10:20 PM
The stateflow is a member variable, so I'd think the function would be kept there
r

Ryan Rolnicki

05/13/2021, 11:28 PM
What is T? If you emit an object that 'equals' the previous value it won't actually do anything.,
Here's an example: https://pl.kotl.in/OXQVvI06w
d

dan.the.man

05/14/2021, 12:19 AM
The objects aren't equal
2 Views