Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question] Async action with combine #27

Closed
nielstj opened this issue Jun 3, 2020 · 5 comments
Closed

[Question] Async action with combine #27

nielstj opened this issue Jun 3, 2020 · 5 comments

Comments

@nielstj
Copy link

nielstj commented Jun 3, 2020

Thank you for writing this library, I'm new to this architecture and trying to make it works.
However I'm struggling to implement an async task for reducer.

For example:
in Counter actions, make a GET call to remote server and then increase count with the response.

Can you please show the proper way to do async / side effect operation?

@alexdrone
Copy link
Owner

Store is based on NSOperation and actions are async by default.

struct GetAction: ActionProtocol {
  func reduce(context: TransactionContext<Store<Counter>, Self>) {
    aynchronousFunctionCallWithCallback(...) { result in
      context.reduceModel { $0.count += result }
      context.fulfill()
    }
  }
}

Simply call context.fulfill() or reject() whenever your operation is finished.

@nielstj
Copy link
Author

nielstj commented Jun 4, 2020

Understood, so it doesn't support combine publisher right now? Thank you for such swift reply.

@alexdrone
Copy link
Owner

You can absolutely use combine publishers.

struct FetchPostsAction: ActionProtocol {
  let url: URL
  private var cancellable: AnyCancellable?

  func reduce(context: TransactionContext<Store<Feed>, Self>) {
    cancellable = URLSession.shared.dataTaskPublisher(for: url)
    .map { $0.data }
    .decode(type: [Post].self, decoder: JSONDecoder())
    .replaceError(with: [])
    .eraseToAnyPublisher()
    .sink(receiveValue: { posts in
      context.reduceModel { $0.posts = posts }
    })
  }
  func cancel(context: TransactionContext<Store<Feed>, Self>) {
    cancellable.cancel()
  }
}

@alexdrone
Copy link
Owner

PS: I've added a hackernews client as a demo

https://github.com/alexdrone/Store/tree/master/Demo/store_hacker_news

@nielstj
Copy link
Author

nielstj commented Jun 8, 2020

Got it... thank you for the guidance!.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants