Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a @State into a Publisher

I want to use a @State variable both for the UI and for computing a value.

For example, let's say I have a TextField bound to @State var userInputURL: String = "https://". How would I take that userInputURL and connect it to a publisher so I can map it into a URL.

Pseudo code:

$userInputURL.publisher()
      .compactMap({ URL(string: $0) })
      .flatMap({ URLSession(configuration: .ephemeral).dataTaskPublisher(for: $0).assertNoFailure() })
      .eraseToAnyPublisher()
like image 891
Ryan Avatar asked Jul 04 '19 01:07

Ryan


2 Answers

You can't convert @state to publisher, but you can use ObservableObject instead.

import SwiftUI

final class SearchStore: ObservableObject {
    @Published var query: String = ""

    func fetch() {
        $query
            .map { URL(string: $0) }
            .flatMap { URLSession.shared.dataTaskPublisher(for: $0) }
            .sink { print($0) }
    }
}

struct ContentView: View {
    @StateObject var store = SearchStore()

    var body: some View {
        VStack {
            TextField("type something...", text: $store.query)
            Button("search") {
                self.store.fetch()
            }
        }
    }
}
like image 188
Mecid Avatar answered Oct 09 '22 22:10

Mecid


You can also use onChange(of:) to respond to @State changes.

struct MyView: View {

  @State var userInputURL: String = "https://"

  var body: some View {
    VStack {
      TextField("search here", text: $userInputURL)
    }
    .onChange(of: userInputURL) { _ in
      self.fetch()
    }
  }

  func fetch() {
    print("changed", userInputURL)
    // ...
  }
}

Output:

changed https://t
changed https://ts
changed https://tsr
changed https://tsrs
changed https://tsrst
like image 37
Daniel R Avatar answered Oct 09 '22 22:10

Daniel R