Show an interactive weight goal chart in a paywall

Follow this recipe to display the projected weight of each user as a chart in a paywall flow. The user enters their current and goal weight in an onboarding flow. Your app collects both values. The chart shows the weekly progress that the user can expect with your app, from one value to the other. Your app renders the chart as a native view in a custom element. On iOS, the view uses Swift Charts. On Android, the view draws the chart without a chart library.

Before you start

  • Update your app to Adapty Kotlin Multiplatform SDK 4.4.0-beta.1 or later. Earlier SDK versions show the fallback content for every custom element.
  • Set up your app to fetch and display flows.
  • Set up the native code of your app for custom elements, as in the Kotlin Multiplatform guide.
  • On iOS, the drag along the chart needs iOS 17 or later. On iOS 16, users see the line, but can’t drag along it.
  • On Android, set up your Android project, including Jetpack Compose. The chart in this recipe is a composable. If your app doesn’t use Compose Multiplatform, add Compose Foundation to the androidMain dependencies, from androidx.compose.foundation:foundation, without a version. The Compose BOM of io.adapty:android-ui sets the version.

Create two separate flows — one for the onboarding, and one for the paywall. Add each to a placement. The code in this recipe fetches the paywall flow from the placement with the ID weight_paywall.

1. Ask for the current and goal weight in the onboarding flow

In the Flow & Paywall Builder, add two Number inputs to the onboarding flow:

  • One for the current weight in kilograms, with the Element ID weight.
  • One for the goal weight in kilograms, with the Element ID goal_weight.

To make your app read the weights the same way in every locale, select Integer from the Format dropdown of both inputs. An input sends its value to your app as text, exactly as the user types it. The code in this recipe reads “70.5” and “70,5” differently. Whole numbers have no decimal separator.

To make sure that your app receives both values, end the onboarding flow with a screen that has no inputs. On that screen, add a button with the Close flow action. Inputs send their values when they lose focus or when the user moves to another screen.

2. Add the custom element to the paywall screen

In the paywall flow, add a custom element to a screen, and set it up for the chart:

  • Type: line_chart.
  • ID: weight_goal.
  • Height: Keep the default Fixed height. The chart fills the custom element.

Keep the custom element out of containers that respond to touch, such as a carousel, so that only the chart responds to a drag along it.

Inside the custom element, add an Image with a sample weight chart. Users see it as the fallback when their version of your app doesn’t display the chart.

3. Save the current and goal weight in your app

Collect the current and goal weight from the flow_user_input events of the onboarding flow, as in Process data from flows. To know that the user reached the last screen, watch for a flow_screen_showed event with is_last_screen set to true. When the onboarding flow closes after that screen, pass the current and goal weight to showWeightPaywall, the function that opens the paywall flow with the chart.

One observer receives the events of both flows. Register it with AdaptyUI.setFlowsEventsObserver before you present the onboarding flow. The observer that you register replaces the previous one: if your app already registers an observer, add the code of WeightFlowsObserver to it. The showWeightPaywall function comes from step 6.

import com.adapty.kmp.AdaptyUI
import com.adapty.kmp.AdaptyUIFlowsEventsObserver
import com.adapty.kmp.models.AdaptyUIFlowView
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive

class WeightFlowsObserver : AdaptyUIFlowsEventsObserver {
    private val enteredWeights = mutableMapOf<String, String>()
    private var reachedLastScreen = false

    override fun flowViewDidReceiveAnalyticEvent(
        view: AdaptyUIFlowView,
        name: String,
        paramsJsonString: String,
    ) {
        val params = Json.parseToJsonElement(paramsJsonString).jsonObject
        if (name == "flow_screen_showed" && params["is_last_screen"]?.jsonPrimitive?.booleanOrNull == true) {
            reachedLastScreen = true
            return
        }
        if (name != "flow_user_input") return
        val elementId = params["element_id"]?.jsonPrimitive?.contentOrNull ?: return
        val value = params["value"]?.jsonPrimitive?.contentOrNull ?: return
        enteredWeights[elementId] = value
    }

    override fun flowViewDidDisappear(view: AdaptyUIFlowView) {
        // This observer receives events from both flows. Reset the entered
        // current and goal weight whenever a flow disappears, so that the paywall doesn't open
        // again when the user closes it.
        val weights = enteredWeights.toMap()
        val finished = reachedLastScreen
        enteredWeights.clear()
        reachedLastScreen = false

        // number inputs send their values as strings
        val currentWeight = weights["weight"]?.toDoubleOrNull()
        val goalWeight = weights["goal_weight"]?.toDoubleOrNull()
        if (!finished || currentWeight == null || goalWeight == null) return

        showWeightPaywall(currentWeight, goalWeight) // defined in step 6
    }
}

// call at app launch, before you present the onboarding flow
fun registerWeightFlowsObserver() {
    AdaptyUI.setFlowsEventsObserver(WeightFlowsObserver())
}

4. Create the chart view

Create a model of a weight plan, and a view with the chart. The plan has one entry per week, from the current weight to the goal weight. When the user drags along the chart, the view marks the week at the touch point, and displays the projected weight for that week:

import Charts
import SwiftUI

struct WeightPlan {
    let entries: [WeightEntry]

    // One entry per week, from the current weight to the goal weight
    init(currentWeight: Double, goalWeight: Double) {
        let weeklyChange = 0.5 // kg per week
        let startDate = Date.now
        let weeks = Int((abs(goalWeight - currentWeight) / weeklyChange).rounded(.up))
        let step = goalWeight < currentWeight ? -weeklyChange : weeklyChange
        entries = (0...weeks).map { week in
            WeightEntry(
                date: startDate.addingTimeInterval(Double(week) * 7 * 24 * 60 * 60),
                kilograms: week == weeks ? goalWeight : currentWeight + step * Double(week)
            )
        }
    }
}

struct WeightEntry: Identifiable {
    let date: Date
    let kilograms: Double
    var id: Date { date }
}

@available(iOS 16.0, *) // Swift Charts needs iOS 16
struct WeightGoalChart: View {
    let entries: [WeightEntry]
    @State private var selectedDate: Date?

    // The entry closest to the date that the user drags to
    private var selectedEntry: WeightEntry? {
        guard let selectedDate else { return nil }
        return entries.min {
            abs($0.date.timeIntervalSince(selectedDate)) < abs($1.date.timeIntervalSince(selectedDate))
        }
    }

    var body: some View {
        if #available(iOS 17.0, *) {
            chart.chartXSelection(value: $selectedDate)
        } else {
            chart // iOS 16: no drag selection
        }
    }

    private var chart: some View {
        Chart {
            ForEach(entries) { entry in
                LineMark(
                    x: .value("Date", entry.date),
                    y: .value("Weight", entry.kilograms)
                )
            }
            if let selectedEntry {
                RuleMark(x: .value("Date", selectedEntry.date))
                    .foregroundStyle(.gray.opacity(0.3))
                PointMark(
                    x: .value("Date", selectedEntry.date),
                    y: .value("Weight", selectedEntry.kilograms)
                )
                .annotation(position: .top) {
                    Text("\(selectedEntry.kilograms, specifier: "%.1f") kg")
                        .font(.caption.bold())
                }
            }
        }
        .chartYScale(domain: .automatic(includesZero: false))
    }
}

The drag along the chart needs iOS 17 or later. On iOS 16, users see the line, but can’t drag along it.

The plan assumes that the weight changes by 0.5 kg per week. To use another rate, edit weeklyChange.

5. Match the chart to the custom element

In your app-wide resolver, add a WeightPlanStore property. Then return the chart view for the line_chart Type and the weight_goal ID. The highlighted lines show what to add or change. If your app has no app-wide resolver yet, copy the whole code:

import AdaptyUIBuilder
import SwiftUI

// the weight plan that your shared code sends before the paywall flow opens
@MainActor
final class WeightPlanStore {
    var plan: WeightPlan?
}

struct CustomElementsResolver: AdaptyUICustomElementsResolver {
    let weightPlanStore: WeightPlanStore

    func view(
        forType type: String,
        id: String,
        context: AdaptyUICustomElementContext
    ) -> AnyView? {
        switch type {
        case "line_chart" where id == "weight_goal":
            guard #available(iOS 16.0, *), let plan = weightPlanStore.plan else {
                return nil // no weight plan: show the fallback
            }
            return AnyView(WeightGoalChart(entries: plan.entries))
        // the other cases of your resolver
        default:
            return nil
        }
    }
}

Until your shared code sends the current and goal weight to your native code, the resolver returns no view, and users see the fallback.

6. Send the current and goal weight from your shared code

Set the resolver at app launch, and fill the store from your shared code. Your shared code can’t call your Swift code or the MainApplication class. To fill the store, declare an interface in your shared code, and implement it in the WeightPlanStore class of each platform.

In commonMain, declare the interface, and an object that holds the store of the current platform:

// the weight plan store of each platform implements this interface
interface WeightPlanReceiver {
    fun setWeights(currentWeight: Double, goalWeight: Double)
}

object WeightPlanBridge {
    // the platform code sets the receiver at app launch
    var receiver: WeightPlanReceiver? = null
}

Implement the interface for each platform:

Make WeightPlanStore conform to the WeightPlanReceiver protocol from your shared framework, such as ComposeApp. The highlighted lines show what to add:

import ComposeApp

// the weight plan that your shared code sends before the paywall flow opens
@MainActor
final class WeightPlanStore: WeightPlanReceiver {
    var plan: WeightPlan?

    // your shared code can call this method on any thread
    nonisolated func setWeights(currentWeight: Double, goalWeight: Double) {
        // the resolver reads the weight plan on the main thread
        Task { @MainActor in
            self.plan = WeightPlan(currentWeight: currentWeight, goalWeight: goalWeight)
        }
    }
}

In iOSApp.swift, add a property for the weight plan to your AppDelegate class. Set the resolver and the receiver in the application(_:didFinishLaunchingWithOptions:) method. The highlighted lines show what to add. Keep the rest of the AppDelegate class as it is:

import AdaptyUI
import ComposeApp
import SwiftUI

class AppDelegate: UIResponder, UIApplicationDelegate {
    // the weight plan that your shared code sends
    let weightPlanStore = WeightPlanStore()

    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        AdaptyUI.setCustomElementsResolver(CustomElementsResolver(weightPlanStore: weightPlanStore))
        WeightPlanBridge.shared.receiver = weightPlanStore
        // the rest of your launch code
        return true
    }
}

In your shared code, send the current and goal weight to the store before the paywall flow opens:

import com.adapty.kmp.Adapty
import com.adapty.kmp.AdaptyUI
import com.adapty.kmp.models.onError
import com.adapty.kmp.models.onSuccess
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

private val mainUiScope = MainScope()

fun showWeightPaywall(currentWeight: Double, goalWeight: Double) {
    mainUiScope.launch {
        // the native resolver builds the chart from the current and goal weight
        WeightPlanBridge.receiver?.setWeights(currentWeight, goalWeight)
        Adapty.getFlow("weight_paywall")
            .onSuccess { flow ->
                AdaptyUI.createFlowView(flow)
                    .onSuccess { view -> view.present() }
                    .onError { error ->
                        // handle the error
                    }
            }
            .onError { error ->
                // handle the error
            }
    }
}

7. Test on a device

The Flow & Paywall Builder can’t run your app code, so its canvas only shows the fallback. To preview the chart:

  1. Publish both flows. To see the latest published versions instead of cached ones, register the device as a test device.
  2. Run a build of your app that includes the resolver. On iOS, use a device with iOS 17 or later. Complete the onboarding flow with a current and a goal weight. Verify that the line of the chart starts at the current weight and ends at the goal weight.
  3. Drag along the chart, and verify that the projected weight for the week under your finger appears above the line.

To test the fallback, return no view for the line_chart Type, and open the paywall flow again.

To find out why the fallback appears instead of the chart, follow the instructions in the Test on a device section of the Kotlin Multiplatform guide.