Process the data
When using Stream, Gravity will fetch and update your views, but you'll need to convert that Data
into useful objects. Sometimes, Gravity can do that automatically for you if this Data
can be represented as JSON. But otherwise, you'll be asked to provide a system to encode and decode data.
To process the data, you'll need to provide the methods to transform the received data into any object.
Creating a data processor
The first thing you'll want is to subclass Streamable
, the class that defines the shared behavior that is common to all data processors. Make sure to define the returned type of object when subclassing Streamable
. In this example, we'll create a very basic data processor that receives data from the socket and convert it as a plain String
:
class StringStreamProcessor: Streamable<String> { // Override the encode method override func encode(value: String) throws -> Data { return value.data(using: .utf8)! } // Override the decode method override func decode(message: Data) throws -> String { return String(data: message, encoding: .utf8) ?? "None" }}
Using the data processor
Once we've defined our data processor, we can use it simply by passing an instance as an argument in the GravityStream
property wrapper:
@GravityStream(url: "wss://example.org/api/endpoint", processor: StringStreamProcessor()) var api