简体   繁体   中英

How do I print subscribed dictinary value in RxSwift?

I have an Observable that returns a dictionary :

func myFunc() -> Observable<[String : MyClass]> {
    return service.getDictionary()
}

How do I get ahold of the keys and values ?

viewModel.myFunc().subscribe(onNext: {
    print("🐱", $0 )
}).disposed(by: disposeBag)

There's no property like .key or .value . Do I use map or flatMap or how does it work?

RxSwift 5.0 Tested

    func myFunc() -> Observable<[String : String]> {
        let dict:[String:String] = ["key0": "value0", "key1": "value1", "key2": "value2","key3" : "value3"]
        return Observable.just(dict)
    }


    myFunc()
    .map { (dict) -> [(String,String)] in
            let keys = Array(dict.keys)
            var key_value_array = Array<(String,String)>()
            for key in keys {
                let key_value_tuple = (key,dict[key]!)
                key_value_array.append(key_value_tuple)
            }

        return key_value_array
    }.flatMap { Observable.from($0) }
        .subscribe(onNext: { (tuple) in
        print("Key is \(tuple.0)")
        print("Value is \(tuple.1)")
    }).disposed(by: disposeBag)

Then log in console is

Key is key0
Value is value0
Key is key1
Value is value1
Key is key3
Value is value3
Key is key2
Value is value2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM