Code Monkey home page Code Monkey logo

rex's Introduction

No Maintenance Intended

⚠️ Deprecated ⚠️

This repo is no longer being maintained. It has been supersede by:

  1. ReactiveSwift: for core operators.
  2. ReactiveCocoa: for UI operators.

Some operators have not been ported. If something is amiss, please open a PR, or an issue, in the corresponding repo. ❤️

Thanks!


Rex Carthage compatible

Extensions for ReactiveCocoa that may not fit in the core framework.

New development targets RAC 4/Swift 2/Xcode 7. For RAC 3 support see the 0.5 release.

Signal

All Signal operators are available for SignaProducers too via explicit lifting.

filterMap

Applies transform to values from signal with non-nil results unwrapped and forwared on the returned signal. This is equivalent to map { … } .filter { $0 != nil } .map { $0! } but without creating extra intermediate signals.

func filterMap<U>(transform: T -> U?) -> Signal<U, E>
ignoreError

Wraps a signal in a version that drops Error events. By default errors are replaced with a Completed event but Interrupted can also be specified as replacement.

func ignoreError(#replacement: Event<T, NoError> = .Completed) -> Signal<T, NoError>
timeoutAfter

Forwards events from signal until it terminates or until interval time passes. This is nearly identical to timeoutWithError from RAC except any terminating event can be used for the timeout.

func timeoutAfter(interval: NSTimeInterval, withEvent event: Event<T, E>, onScheduler scheduler: DateSchedulerType) -> Signal<T, E>
uncollect

Flattens batches of elements sent on signal into each individual element. The inverse of collect. Requires signal values to conform to SequenceType.

func uncollect() -> Signal<T.Generator.Element, E>

SignalProducer

Operators specific to SignalProducer.

groupBy

Partitions values from producer into new producer groups based on the key returned from grouping. Termination events on the original producer are forwarded to each inner producer group.

func groupBy<K: Hashable>(grouping: T -> K) -> SignalProducer<(K, SignalProducer<T, E>), E>

UIKit Extensions

UIButton.rex_pressed

Flexible way to bind CocoaAction to the press of button. In addition the button will be disabled during the Action executing. Such behavior is convenient for tasks that require some time, like a download process in the example below.

let downloadAction = Action<UIButton, NSData, NSError> { _ in
    let url = NSURL(string: "https://github.com/RACCommunity/Rex/archive/master.zip")
    let request = NSURLRequest(URL: url!)
    return NSURLSession.sharedSession().rac_dataWithRequest(request).map { $0.0 }
}

downloadButton.rex_pressed.value = downloadAction.unsafeCocoaAction

License

Rex is released under the MIT license

rex's People

Contributors

335g avatar andersio avatar andwaredev-zz avatar aschuch avatar bhstrifork avatar bjarkehs avatar dmcrodrigues avatar e-kazakov avatar eofs avatar ikesyo avatar iv-mexx avatar ktakayama avatar larryonoff avatar mbuchetics avatar mdiep avatar neilpa avatar ruiaaperes avatar sharplet avatar skyylex avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rex's Issues

carthage bootstrap NSInvalidArgumentException

Using master, both "carthage bootstrap" and "carthage update" both yield the error:

uncaught exception 'NSInvalidArgumentException', reason: 'working directory doesn't exist.' 

It looks similar to Carthage/Carthage#745 However, changing the Cartfile to different things didn't help.

The Rex Cartfile is identical to something I am using for a private project and it works fine there. So, something deeper is happening here.

More Cocoa extensions

Currently I've been adding things as needed but there's a lot in RAC 2 that should be ported.

Thank you

Just wanted to say thank you for maintaining this repo. Very helpful in MVVM patterns. Cheers!

New release for RC1?

Hi,

I just wanted to ask if we should aim for a new release with the release of RC1 or simply stick with alpha 4, since there were only bugfixes in RC1?

Generic print method

I'm going to write more generic print method, but don't know what to do with .Next and .Error. I cannot just call signal |> print(.Next) or signal |> print(.Error). These cases need to be called with arguments. Could you please help? Should I implement additional enum?

See the actual code below.

public func print<T, E>(_ event: Event<T, E>? = nil)(signal: SignalProducer<T, E>) -> SignalProducer<T, E> {
    return signal
        |> on(event: { aEvent in
            if let event = event {
                switch (aEvent, event) {
                case (.Next, .Next):
                    println(aEvent)

                case (.Error, .Error):
                    println(aEvent)

                case (.Completed, .Completed):
                    println(aEvent)

                case (.Interrupted, .Interrupted):
                    println(aEvent)

                default:
                    break
                }
            } else {
                println(aEvent)
            }
        })
}

How can I handle error flow when I bind action to rex_pressed.value

I want to show error popup when an error happened to signal. How can I handle SignalProducer errors to show error to user?

let emailAndPasswordChecksSignal = emailTextSignal.combineLatestWith(passTextSignal)
        .flatMap(.Merge) { (email, password) -> SignalProducer<(), TextFieldErrorType> in
            if email == nil || email?.characters.count < 1 {
                return SignalProducer<(), TextFieldErrorType>(error: .EmailIsNotCorrect)
            }
            if password == nil || password?.characters.count < 1 {
                return SignalProducer<(), TextFieldErrorType>(error: .PasswordIsEmpty)
            }
            return SignalProducer<(), TextFieldErrorType>(value: ())
        }

        let loginAction = Action<UIButton, (), TextFieldErrorType> { _ in
            return emailAndPasswordChecksSignal
        }

Fill with Next(value) event with interval.

I use MutableProperty to fill values coming through a Bluetooth protocol, and them being represented at real-time in different sections of the application.

I was thinking (and maybe it could be useful to add in this library) a method which fills a producer or signal with .Next(value) events eachtime the original producer or signal doesn't send any value for a NSTimeInterval. Using the DateSchedulerType shouldn't be hard to achieve this behavior.
When the signal or the producer sends again a value, the "Default" event is replaced inmediately and the countdown starts again.

What do you think?

Transfer ownership to RACCommunity

I'm not currently doing iOS development in my day job and as a result haven't been able to maintain this library to the degree I would like. There's been discussions about moving Rex under the ReactiveCocoa org and it effectively becoming RAC5 since it provides the missing Swift Cocoa bindings. IMO, moving to RACCommunity would be a good first step in that transition. It'll ease the maintenance burden I haven't kept up with and provide a staging area to prep for the RAC5 transition.

/cc @RuiAAPeres @mdiep @RACCommunity

rex_text in UITextView is not called for initial value

I know that all this will be changed in nearest future, but in any case rex has following issue.

      self.textView.text = "Hello world"
      self.textView
         .rex_text
         .startWithNext { _ in
            //is not called for "Hello world"
      }

Incompatible RAC 4.2.1 with Rex 0.10.0

Hello! With the last release of RAC (4.2.1) and Rex(0.10.0), I get the following error:
/Carthage/Checkouts/Rex/Source/SignalProducer.swift:84:23: error: ambiguous use of 'debounce(_:onScheduler:)'

I've solved it by fixing RAC version in 4.2.0

github "ReactiveCocoa/ReactiveCocoa" == 4.2.0
github "neilpa/Rex" ~> 0.10.0

Maybe you could make a new release to be compatible with 4.2.1? Thank you!

Use gyb from the Swift project for the AppKit/UIKit extensions

The MutableProperty wrappers are effectively copy & pasted with a few tweaks here & there for types, associated keys, and so on. It would be wise to figure out a way to use the gyb (Generate Your Boilerplate) tool from the Swift project to help us overcome a lot of that (sadly necessary) boilerplate.

What properties are added to Rex?

How do you define UI properties that are in Rex.

E.g. Can we expect UIButton rex_image property or UIPageControl rex_currentPage? Or very useful NSLayoutConstraint rex_constant and rex_priority properties?

Sure UIKit has lots of different properties and adding them all will make this simple tiny library very complex. But I think there are still lots of often used that can be also added

Thanks!

Port specialized repeat operators

// Delays repeating a signal for the specified interval after each completion.
- (RACSignal*) delayedRepeat:(NSTimeInterval)interval;

// Repeats a signal until a desired value is found. All of the non-matches
// are filtered out. Once the first value matching predicate is found that
// value is sent and the signal completes. This is useful in polling scenarios
// where you can't map the non-desired values into errors.
- (RACSignal*) repeatUntil:(BOOL(^)(id next))predicate;

// Same as -repeatUntil: but with a delay between repetitions.
- (RACSignal*) repeatUntil:(BOOL(^)(id next))predicate delay:(NSTimeInterval)interval;

Allow to associate any type of object

Very useful to associate any type of object: structs/enums
currently associatedObject allows to associate just AnyObject instances

private class Box<T> {
   let unbox: T
   init(_ value: T) {
      self.unbox = value
   }
}

extension NSObject {
   public final func associatedObject<T>(key key: UnsafePointer<()>, @noescape initial: () -> T) -> T {
      if let boxedObject = objc_getAssociatedObject(self, key) as? Box<T> {
         return boxedObject.unbox
      }
      let object = initial()
      objc_setAssociatedObject(self, key, Box(object), .OBJC_ASSOCIATION_RETAIN)
      return object
   }
}

Update bundle name

Should we update the bundle name from me.neilpa now that the repo is under RACCommunity?

rex_text extensions seems to leave behind persistent objects

Setup: I have a UICollectionView with 4 UICollectionViewCell's that contain a UILabel

class SectionBarCollectionViewCell: UICollectionViewCell, ReactiveView {

    static let DefaultIdentifier = "identifier"
    var viewModel = MutableProperty<SectionBarCellViewModel?>(nil)
    let titleLabel = Label()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit() {
        contentView.addSubview(titleLabel)
        bindObservers()
    }

    func bindObservers() {

        titleLabel.rex_text <~ viewModel.producer |> flatMap(.Latest) { $0?.title.producer ?? SignalProducer(value: "") } |> ignoreNil
    }

    func bindViewModel(viewModel: AnyObject) {
        if let viewModel = viewModel as? SectionBarCellViewModel {

            self.viewModel.put(viewModel)
        }
    }
}

when I profile my application it seems that the UILabel won't get destroyed when the UICollectionViewCell's are deinit
screen shot 2015-08-20 at 15 30 30

if i do it without binding, it destroys the UILabel as suspected when the Cell is deinit.

viewModel.producer |> flatMap(.Latest) { $0?.title.producer ?? SignalProducer(value: "") } |> start(next: {[unowned self] title in self.titleLabel.text = title })

How does one use rex_pressed?

I'm not sure how i can use rex_pressed, since its value is a CocoaAction

I made my own extension to receive events on a TouchUpInside

extension UIButton {

    public var rac_press: Signal<UIButton,NoError> {
        return associatedObject(self, &press, { _ in

            let action = Action<UIButton,UIButton,NoError>{ input in
                SignalProducer(value: input)
            }

            self.addTarget(action.unsafeCocoaAction, action: CocoaAction.selector, forControlEvents: .TouchUpInside)

            return action.values
        })
    }
}

private var press: UInt8 = 0

Does this makes sense? or do i misinterpret your rex_pressed?

Rex 0.10 missing UIDatePicker.rex_date from framework binaries

I wanted to create a PR for this. But I cloned the repository and checked if the related file (Source/UIKit/UIDatePicker.swift) is included in the iOS framework target. Alas, it is! Now I'm at a loss why the UIDatePicker extension is not included in the generated header file for Rex. Any ideas?

New tag for RAC 4 alpha 3

Hi,

Would you be willing to create a new tag for the alpha 3 so that it can be easily targeted? Or should I assume that 0.9.0-alpha.2 would be good enough?

Print operators

public func printAll<T, E>(signal: SignalProducer<T, E>) -> SignalProducer<T, E> {
    return signal
        |> on(started: { println("started") }, error: { println("error: \($0)") }, completed: { println("completed") }, interrupted: { println("interrupted") }, next: { println("next \($0)") })
}
public func printNext<T, E>(signal: SignalProducer<T, E>) -> SignalProducer<T, E> {
    return signal
        |> on(next: { println("next \($0)") })
}
public func printError<T, E>(signal: SignalProducer<T, E>) -> SignalProducer<T, E> {
    return signal
        |> on(error: { println("error: \($0)") })
}

ignoreError operator

public func ignoreError<T, E>(signal: Signal<T, E>) -> Signal<T, NoError> {
    return Signal { observer in
        return signal.observe(Signal.Observer { event in
            switch event {
            case let .Next(value):
                sendNext(observer, value.value)
            case let .Error(error):
                break
            case .Completed:
                sendCompleted(observer)
            case .Interrupted:
                sendInterrupted(observer)
            }
        })
    }
}

EXC_BAD_ACCESS when using rex_enabled with <~ operator

Hi,

trying to bind an AnyProperty<Bool> to a UIButton.rex_enabled by using <~ and experienced EXC_BAD_ACCESS. I played around and it seems that this also crashes when only accessing UIButton.rex_enabled

initial Code:

    override func viewDidLoad() {
        loginButton.rex_enabled <~ loginViewModel.validCredentials
        super.viewDidLoad()
    }

this crashes also:

    override func viewDidLoad() {
        loginButton.rex_enabled
        super.viewDidLoad()
    }

loginButton comes from an @IBOutlet and I can confirm that there is no issue with the button instance.

Do I miss anything here or is this a bug?

ReactiveCocoa 4.2.0
Rex 0.10.0
Result 2.0.0
xCode 7.3.1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.