Last active
November 11, 2020 10:59
-
-
Save ha1f/5aaf887c41d03b12131070b4a8d246f5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// PhotoLibraryChangeObserver.swift | |
// ha1fAlbum | |
// | |
// Created by はるふ on 2018/10/29. | |
// Copyright © 2018年 はるふ. All rights reserved. | |
// | |
import Photos | |
import RxSwift | |
import RxCocoa | |
/// We need this class to hide PHPhotoLibraryChangeObserver methods. | |
private final class PhotoLibraryChangeObserverSink: NSObject { | |
fileprivate let _publish = PublishRelay<PHChange>() | |
} | |
extension PhotoLibraryChangeObserverSink: PHPhotoLibraryChangeObserver { | |
func photoLibraryDidChange(_ changeInstance: PHChange) { | |
_publish.accept(changeInstance) | |
} | |
} | |
final class PhotoLibraryChangeObserver: NSObject { | |
fileprivate let _sink = PhotoLibraryChangeObserverSink() | |
fileprivate let _photoLibrary: PHPhotoLibrary | |
init(photoLibrary: PHPhotoLibrary = PHPhotoLibrary.shared()) { | |
_photoLibrary = photoLibrary | |
super.init() | |
} | |
deinit { | |
_photoLibrary.unregisterChangeObserver(_sink) | |
} | |
} | |
extension Reactive where Base == PhotoLibraryChangeObserver { | |
var photoLibraryDidChange: Observable<PHChange> { | |
return base._sink._publish | |
.do(onSubscribed: { [weak base] in | |
guard let base = base else { | |
return | |
} | |
base._photoLibrary.register(base._sink) | |
}, onDispose: { [weak base] in | |
guard let base = base else { | |
return | |
} | |
base._photoLibrary.unregisterChangeObserver(base._sink) | |
}) | |
} | |
} |
nice snippet, thanks for sharing!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example