1 /*
2  * Copyright (C) 2024 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.example.tracing.demo.experiments
17 
18 import com.android.app.tracing.coroutines.createCoroutineTracingContext
19 import com.example.tracing.demo.FixedThreadA
20 import javax.inject.Inject
21 import javax.inject.Singleton
22 import kotlinx.coroutines.CoroutineDispatcher
23 import kotlinx.coroutines.CoroutineScope
24 import kotlinx.coroutines.coroutineScope
25 import kotlinx.coroutines.flow.SharingStarted
26 import kotlinx.coroutines.flow.shareIn
27 
28 @Singleton
29 class LeakySharedFlow
30 @Inject
31 constructor(@FixedThreadA private var dispatcherA: CoroutineDispatcher) : Experiment {
32 
33     override val description: String = "Create a shared flow that cannot be cancelled by the caller"
34 
35     private val leakedScope =
36         CoroutineScope(dispatcherA + createCoroutineTracingContext("flow-scope"))
37 
startnull38     override suspend fun start() {
39         // BAD - does not follow structured concurrency. This creates a new job each time it is
40         // called. There is no way to cancel the shared flow because the parent does not know about
41         // it
42         coldCounterFlow("leaky1").shareIn(leakedScope, SharingStarted.Eagerly, replay = 10)
43 
44         // BAD - this also leaks
45         coroutineScope {
46             coldCounterFlow("leaky2").shareIn(leakedScope, SharingStarted.Eagerly, replay = 10)
47         }
48     }
49 }
50