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 android.os.Trace 19 import com.android.app.tracing.coroutines.flow.collectTraced 20 import com.android.app.tracing.coroutines.flow.filterTraced as filter 21 import com.android.app.tracing.coroutines.flow.flowName 22 import com.android.app.tracing.coroutines.flow.mapTraced as map 23 import com.android.app.tracing.coroutines.launchTraced as launch 24 import com.example.tracing.demo.FixedThreadA 25 import com.example.tracing.demo.FixedThreadB 26 import com.example.tracing.demo.FixedThreadC 27 import javax.inject.Inject 28 import javax.inject.Singleton 29 import kotlinx.coroutines.CoroutineDispatcher 30 import kotlinx.coroutines.coroutineScope 31 import kotlinx.coroutines.flow.flowOn 32 33 @Singleton 34 class CollectFlow 35 @Inject 36 constructor( 37 @FixedThreadA private var dispatcherA: CoroutineDispatcher, 38 @FixedThreadB private var dispatcherB: CoroutineDispatcher, 39 @FixedThreadC private val dispatcherC: CoroutineDispatcher, 40 ) : Experiment { 41 override val description: String = "Collect a cold flow with intermediate operators" 42 43 private val coldFlow = 44 coldCounterFlow("count", 4) 45 .flowName("original-cold-flow-scope") 46 .flowOn(dispatcherA) <lambda>null47 .filter("evens") { 48 forceSuspend("B", 20) 49 it % 2 == 0 50 } 51 .flowOn(dispatcherB) 52 .flowName("even-filter-scope") <lambda>null53 .map("3x") { 54 forceSuspend("C", 15) 55 it * 3 56 } 57 .flowOn(dispatcherC) 58 <lambda>null59 override suspend fun start(): Unit = coroutineScope { 60 launch(context = dispatcherA) { 61 coldFlow.collectTraced { 62 Trace.instant(Trace.TRACE_TAG_APP, "got: $it") 63 forceSuspend("A2", 60) 64 } 65 } 66 } 67 } 68