1 package com.android.onboarding.contracts
2 
3 import android.content.Intent
4 
5 /**
6  * Interface implemented by a [OnboardingActivityApiContract] to allow it to be used with
7  * [findExecutingContract].
8  *
9  * This allows a single activity to implement multiple contracts, as long as those contracts can be
10  * distinguished based on properties of the [Intent].
11  *
12  * Recommended usage:
13  * ```
14  * val contracts = arrayOf(RedContract(), BlueContract(), GreenContract())
15  * val contract = intent?.findExecutingContract(*contracts) ?: RedContract()
16  * ```
17  */
18 interface IdentifyExecutingContract {
19   /** Returns true if this [OnboardingActivityApiContract] is currently executing. */
isExecutingnull20   fun isExecuting(intent: Intent): Boolean
21 }
22 
23 /**
24  * Find which of multiple non-overlapping contracts are executing.
25  *
26  * See [IdentifyExecutingContract] for usage.
27  */
28 fun <I : IdentifyExecutingContract> Intent.findExecutingContract(vararg contracts: I) =
29   contracts.firstOrNull { it.isExecuting(this) }
30 
31 /**
32  * More lightweight version of [IdentifyExecutingContract] working with intent actions only.
33  */
34 interface IdentifyExecutingContractByAction : IdentifyExecutingContract {
35   /** Returns true if this [OnboardingActivityApiContract] is currently executing. */
isExecutingnull36   fun isExecuting(action: String?): Boolean
37 
38   override fun isExecuting(intent: Intent): Boolean = isExecuting(intent.action)
39 }
40 
41 /** @see Intent.findExecutingContract */
42 fun <I : IdentifyExecutingContractByAction> findExecutingContract(
43   action: String?,
44   vararg contracts: I,
45 ) = contracts.firstOrNull { it.isExecuting(action) }
46