1 package com.android.onboarding.contracts 2 3 import android.content.Intent 4 5 /** Marks functions that read or write intent data */ 6 @DslMarker internal annotation class IntentManipulationDsl 7 8 /** Interface for writing an object to an [Intent] and reading the same object from an [Intent]. */ 9 interface IntentSerializer<V> { 10 /** 11 * Utility intent builder that allows writing the [arg] and customising the intent settings 12 * 13 * @param arg to serialize into intent extras 14 * @param builder to configure the intent 15 */ 16 @IntentManipulationDsl <lambda>null17 fun Intent(arg: V, builder: Intent.() -> Unit = {}): Intent = <lambda>null18 Intent().also { 19 write(it, arg) 20 it.builder() 21 } 22 23 /** 24 * Utility intent builder that allows writing the [arg] and customising the intent settings 25 * 26 * @param action the intent should send 27 * @param arg to serialize into intent extras 28 * @param builder to configure the intent 29 */ 30 @IntentManipulationDsl <lambda>null31 fun Intent(action: String, arg: V, builder: Intent.() -> Unit = {}): Intent = <lambda>null32 Intent(arg) { 33 this.action = action 34 builder() 35 } 36 writenull37 fun write(intent: Intent, value: V) 38 39 fun read(intent: Intent): V 40 41 /** 42 * Calls [read] to get the value, but instead of throwing an error during read failures it instead 43 * catches it, prints stack trace and returns null 44 */ 45 fun readOrNull(intent: Intent): V? = 46 runCatching { read(intent) }.onFailure(Throwable::printStackTrace).getOrNull() 47 } 48 49 /** 50 * A serializer that does not expose [Intent] directly and instead works via [NodeAwareIntentScope] 51 * abstraction that can be observed 52 * 53 * TODO This is living as a separate opt-in interface for now, but we should look into incorporating 54 * it inside the contract class to make methods enforceable and protected 55 */ 56 interface NodeAwareIntentSerializer<V> : IntentSerializer<V>, NodeAware { NodeAwareIntentScopenull57 fun NodeAwareIntentScope.write(value: V) 58 59 fun NodeAwareIntentScope.read(): V 60 61 override fun write(intent: Intent, value: V): Unit = 62 NodeAwareIntentScope(nodeId, intent).use { it.write(value) } 63 <lambda>null64 override fun read(intent: Intent): V = NodeAwareIntentScope(nodeId, intent).use { it.read() } 65 } 66