Providing Data from Child to Parent in Effect Typescript

Hi, how can child provide something to parent? for example


const child = Effect.gen(function* () {
  /**
   * `SomeMagicProvider` is a hypothetical function that allows child to provide
   * a value to the parent caller without changing the return value of the child effect.
   */
  yield* SomeMagicProvider(ContextParentNeed, 'provided value from child')

  /**
   * This is the default behavior, child returns a value
   * that is used by the parent caller.
   */
  return 'some value' as const
})

const program = Effect.gen(function* () {
  /**
   * Without changing the return value, is it possible for child to provide the data to
   * the parent caller?
   *
   * I dont want to change the return signature, instead i want to use something
   * that parent can use it on child to get the provided value that is transferred upwards.
   *
   * To my knowledge, I have seen Context & Services to be used to provide
   * data downwards: a parent can provide a context to child
   * and child can use that context to get the data.
   */

  const value = yield* child // this is the default behavior, child returns a value
  console.log('Value from child:', value)

  /**
   * Here I am using `SomeMagicExtractor` to extract the provided value from child
   * without changing the return value of the child effect.
   *
   * This is a hypothetical function that extracts the provided value
   * and return a { returnValue, providedValue } object.
   *
   * The `providedValue` is the value that child has provided to parent caller.
   *
   * `ContextParentNeed` is a hypothetical context that a parent needs from the child
   * and `() => 'default value'` is a fallback value in case the child does not provide the value.
   *
   * We cant make it type-safe as child does not know that it is providing a value to parent,
   * so we have to use a fallback value.
   */
  const { returnValue, providedValue } = yield* SomeMagicExtractor(child, ContextParentNeed, () => 'default value')
})
Was this page helpful?