Skip to content

Instantly share code, notes, and snippets.

@jacksonh
Created August 6, 2013 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacksonh/7292c21eac40b79cc76d to your computer and use it in GitHub Desktop.
Save jacksonh/7292c21eac40b79cc76d to your computer and use it in GitHub Desktop.
//
// This is a signal that gets a users password. Imagine that it did something clever, like
// look in the keystore and prompt the user if the password isn't in the store
//
RACSignal *fetchPassword = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
NSString *password = @"the password"; // imagine this required some async work to fetch
[subscriber sendNext:password];
[subscriber sendCompleted];
return [RACDisposable disposableWithBlock:^{
}];
}];
//
// Once we have fetched the password, we want to fetch a
// list of items from a webservice that requires that password
//
[[fetchPassword flattenMap:^RACStream *(NSString *password) {
return [AsyncClient fetchStuffListWithPassword:password];
}] flattenMap:^RACStream *(id stuffItem) {
//
// Now for each item that is in the list, we need to do
// another API call, this one requires the original password
// Ideally, I could pass that password in the flattenMap call
//
return [AsyncClient fetchStuffItem:stuffItem withPassword:password];
}];
@erikprice
Copy link

Hm, that's actually not that simple! How about something like this (totally untested):

[[fetchPassword flattenMap:^id (NSString *password) {

    // I'm not sure whether this works, but the idea
    // is that the signal that returns the password
    // should just keep returning the password continuously
    // so that the -zipWith: doesn't terminate until there
    // are no more stuffItems.
    return [[[RACSignal return:password] never]
                       zipWith:[AsyncClient fetchStuffListWithPassword:password]]

}] flattenMap:^RACSignal *(RACTuple *passwordAndStuffItem) {

    RACTupleUnpack(NSString *password, id stuffItem);
    return [AsyncClient fetchStuffItem:stuffItem withPassword:password];

}];

@jacksonh
Copy link
Author

jacksonh commented Aug 6, 2013

Slight modification on your version. Basically I sub'd repeat for never (never is a class method in my version of RAC), and changed the unpack line a bit:

[[fetchPassword flattenMap:^id (NSString *password) {
    return [[[RACSignal return:password] repeat]
                   zipWith:[AsyncClient fetchStuffListWithPassword:password]]
}] flattenMap:^RACSignal *(RACTuple *passwordAndStuffItem) {
    RACTupleUnpack(NSString *password, id stuffItem) = passwordAndStuffItem;
    return [AsyncClient fetchStuffItem:stuffItem withPassword:password];
}];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment