Chapter 2: Using Live Data issues

When I get to the Live Data section of Chapter 2, I’m bumping into an issue with the appState. When I try to run Preview, I get "Cannot preview this file - Preview is missing environment object “AppState”.

I figured it was user error on my part, but when I open the final project, I encounter the same issue. I compared my code to that in the finalproject folder and they’re functionally the same and both generate that error when trying to preview ContentView.

Upon further investigation, compiling the app the “old fashioned” way and running it with the play button works fine. It does show the events.count if you try to view it on the Canvas in live preview mode.

1 Like

I have mostly avoided using AppState in the previews to avoid hitting the API usage limit. In some files, I specifically said to delete the preview, but maybe I missed one.

You can add .environmentObject(AppState()) to the preview, but be prepared for API errors if you do much editing.

Building and running a macOS app is fast, so I tend to use the preview quite sparingly, for small components. Mostly, I just build & run to see what I’m getting.

Thank you for getting back so quickly! This is a fun book to read. I saw a note in the TableView chapter just now re: avoidance of hitting API usage limits.

1 Like

Solution
Step 1
First, we need to create a class with the name Event to wrap the data that the livedata is exposing. Have a look at how to create an Event class:

In this class, we maintain a flag hasBeenHandled to check whether the data is observed at least once.

Step 2
Now we need to create another class with name EventObserver that extends Observer. Just to make the process of using it simple, have a look:

When new data is posted, the onChanged function is triggered and the flag hasBeenHandled is set to false. As soon as the first subscriber observed the data, the flag hasBeenHandled will be true, so that the rest of the subscribers won’t receive the data and the cycle repeats every time new data is posted.

Step 3
While observing livedata, we need to use EventObserver instead of regular Observer so that handling is simplified. Have a look:

Greeting,
Rachel Gomez

Thanks for posting one possible solution Rachel.
Did you have a GitHub repo or some other link where people could see your code?

Sarah