Skip to content

Commit

Permalink
Removed WithScopedValue
Browse files Browse the repository at this point in the history
  • Loading branch information
iampatbrown committed Jan 28, 2022
1 parent d5e0af6 commit 483c960
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 5 deletions.
12 changes: 9 additions & 3 deletions Examples/DerivedBehavior/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ class AppViewModel: ObservableObject {
}
}

struct CounterTabItem: View {
@ScopedValue(\AppViewModel.counter.count) var count
var body: some View {
Self._printChanges()
return Text("Counter \(self.count)")
}
}

struct ProfileTabItem: View {
@ScopedValue(\AppViewModel.profile.favorites.count) var favoritesCount
var body: some View {
Expand All @@ -32,9 +40,7 @@ struct ContentView: View {
return TabView {
CounterView()
.tabItem {
WithScopedValue(\AppViewModel.counter.count) { count in
Text("Counter \(count)")
}
CounterTabItem()
}

ProfileView()
Expand Down
48 changes: 46 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ A collection of tools for working with observable objects in SwiftUI.

* [Motivation](#motivation)
* [Tools](#tools)
* [Examples](#examples)
* [Installation](#installation)


Expand Down Expand Up @@ -192,7 +191,52 @@ struct CounterView: View {
}
```

## Examples
### Dependency

Similar to SwiftUI's `@Environment` attribute but for observable objects instead of views.

```swift
class TwentySideDie: ObservableObject {
@Dependency(\.numberGenerator) var numberGenerator
@Published var value: Int = 20

func roll() {
self.value = self.numberGenerator.random(in: 1...20)
}
}
```

### Dependencies

Dependencies can be defined by defining a type that conforst to the `DependencyKey` protocol, and then extending the dependencies structure with a new property:

```swift
struct NumberGenerator {
var random: (ClosedRange<Int>) -> Int

func random(in range: ClosedRange<Int>) -> Int {
self.random(range)
}

static let `default` = Self { Int.random(in: $0) }
}

enum NumberGeneratorKey: DependencyKey {
static let defaultValue: NumberGenerator = .default
}

extension Dependencies {
var numberGenerator: NumberGenerator {
get { self[NumberGeneratorKey.self] }
set { self[NumberGeneratorKey.self] = newValue }
}
}
```


### WithDependencies

### withDependencies(\_:\_:)

## Installation

Expand Down

0 comments on commit 483c960

Please sign in to comment.